diff --git a/insight.sln b/insight.sln index c6e0266..4d81ecd 100644 --- a/insight.sln +++ b/insight.sln @@ -31,12 +31,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Server", "src\Serve EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Updater", "src\Updater\Insight.Updater\Insight.Updater.csproj", "{4875D70F-A96B-4EBA-99BE-218886D29BEB}" 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}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Agent.Assets", "src\Agent\Insight.Agent.Assets\Insight.Agent.Assets.csproj", "{4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -71,18 +67,10 @@ Global {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.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.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.Build.0 = Release|Any CPU - {4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -95,9 +83,7 @@ Global {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} - {EBB8A2A8-453B-4867-A8E2-072530391DD0} = {3F000016-069D-477E-ACA3-F643880B57E8} {2A391CA2-F96B-4DB7-80AA-0668A5141640} = {140F73DD-29D3-4C44-809B-5B470880AA0D} - {4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324} = {140F73DD-29D3-4C44-809B-5B470880AA0D} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {F376A326-7590-4E7E-AB9B-76CED8527AB0} diff --git a/src/Agent/Insight.Agent.Assets/Enums/CategoryEnum.cs b/src/Agent/Insight.Agent.Assets/Enums/CategoryEnum.cs deleted file mode 100644 index 5ba8cb9..0000000 --- a/src/Agent/Insight.Agent.Assets/Enums/CategoryEnum.cs +++ /dev/null @@ -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 - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Enums/DispatchEnum.cs b/src/Agent/Insight.Agent.Assets/Enums/DispatchEnum.cs deleted file mode 100644 index 2d824d4..0000000 --- a/src/Agent/Insight.Agent.Assets/Enums/DispatchEnum.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Insight.Agent.Enums -{ - public enum DispatchEnum - { - Pending = 1, - Failure = 2, - Success = 3, - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Enums/StatusEnum.cs b/src/Agent/Insight.Agent.Assets/Enums/StatusEnum.cs deleted file mode 100644 index 49b8e7d..0000000 --- a/src/Agent/Insight.Agent.Assets/Enums/StatusEnum.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Insight.Agent.Enums -{ - public enum StatusEnum - { - Information = 1, - Warning = 2, - Error = 3 - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Insight.Agent.Assets.csproj b/src/Agent/Insight.Agent.Assets/Insight.Agent.Assets.csproj deleted file mode 100644 index 540ca66..0000000 --- a/src/Agent/Insight.Agent.Assets/Insight.Agent.Assets.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net7.0 - true - enable - Insight.Agent.Assets - Insight.Agent - Insight - 2023.9.14.0 - - - - none - - - - none - - - - - - - - - - - - diff --git a/src/Agent/Insight.Agent.Assets/Interfaces/IAgentMessageHandler.cs b/src/Agent/Insight.Agent.Assets/Interfaces/IAgentMessageHandler.cs deleted file mode 100644 index a9e69a6..0000000 --- a/src/Agent/Insight.Agent.Assets/Interfaces/IAgentMessageHandler.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Insight.Agent.Messages; - -namespace Insight.Agent.Interfaces -{ - public partial interface IAgentMessageHandler - { - ValueTask HandleAsync(TSender sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage; - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Application/Application.cs b/src/Agent/Insight.Agent.Assets/Messages/Application/Application.cs deleted file mode 100644 index ba3ad5c..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Application/Application.cs +++ /dev/null @@ -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, IAgentMessage { } - -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Authentication/Authentication.cs b/src/Agent/Insight.Agent.Assets/Messages/Authentication/Authentication.cs deleted file mode 100644 index 84406f4..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Authentication/Authentication.cs +++ /dev/null @@ -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 { } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Commands/Commands.cs b/src/Agent/Insight.Agent.Assets/Messages/Commands/Commands.cs deleted file mode 100644 index b231232..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Commands/Commands.cs +++ /dev/null @@ -1,10 +0,0 @@ -using MemoryPack; - -namespace Insight.Agent.Messages -{ - [MemoryPackUnion(2000, typeof(GetInventory))] - public partial interface IAgentMessage { } - - [MemoryPackable] - public partial class GetInventory : IAgentMessage { } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Console/ConsoleQuery.cs b/src/Agent/Insight.Agent.Assets/Messages/Console/ConsoleQuery.cs deleted file mode 100644 index 369304c..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Console/ConsoleQuery.cs +++ /dev/null @@ -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; } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Drive/Drive.cs b/src/Agent/Insight.Agent.Assets/Messages/Drive/Drive.cs deleted file mode 100644 index 5a2f966..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Drive/Drive.cs +++ /dev/null @@ -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? Volumes { get; set; } - } - - [MemoryPackable(GenerateType.Collection)] - public partial class DriveList : List, 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; } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Event/Event.cs b/src/Agent/Insight.Agent.Assets/Messages/Event/Event.cs deleted file mode 100644 index edd3b61..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Event/Event.cs +++ /dev/null @@ -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 - } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/IAgentMessage.cs b/src/Agent/Insight.Agent.Assets/Messages/IAgentMessage.cs deleted file mode 100644 index 3c3edf0..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/IAgentMessage.cs +++ /dev/null @@ -1,7 +0,0 @@ -using MemoryPack; - -namespace Insight.Agent.Messages -{ - [MemoryPackable] - public partial interface IAgentMessage { } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Interface/Interface.cs b/src/Agent/Insight.Agent.Assets/Messages/Interface/Interface.cs deleted file mode 100644 index 1c008c5..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Interface/Interface.cs +++ /dev/null @@ -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? Addresses { get; set; } - - [MemoryPackOrder(23)] - public List? Gateways { get; set; } - - [MemoryPackOrder(24)] - public List? Dns { get; set; } - - [MemoryPackOrder(25)] - public List? Dhcp { get; set; } - - [MemoryPackOrder(26)] - public List? Routes { get; set; } - } - - [MemoryPackable(GenerateType.Collection)] - public partial class InterfaceList : List, 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; - } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Keepalive/Keepalive.cs b/src/Agent/Insight.Agent.Assets/Messages/Keepalive/Keepalive.cs deleted file mode 100644 index 63588dc..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Keepalive/Keepalive.cs +++ /dev/null @@ -1,10 +0,0 @@ -using MemoryPack; - -namespace Insight.Agent.Messages -{ - [MemoryPackUnion(0, typeof(Keepalive))] - public partial interface IAgentMessage { } - - [MemoryPackable] - public partial class Keepalive : IAgentMessage { } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Mainboard/Mainboard.cs b/src/Agent/Insight.Agent.Assets/Messages/Mainboard/Mainboard.cs deleted file mode 100644 index a86bc5b..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Mainboard/Mainboard.cs +++ /dev/null @@ -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; } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Memory/Memory.cs b/src/Agent/Insight.Agent.Assets/Messages/Memory/Memory.cs deleted file mode 100644 index bb8e444..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Memory/Memory.cs +++ /dev/null @@ -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, 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; } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/OperationSystem/OperationSystem.cs b/src/Agent/Insight.Agent.Assets/Messages/OperationSystem/OperationSystem.cs deleted file mode 100644 index 0fe4ee5..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/OperationSystem/OperationSystem.cs +++ /dev/null @@ -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; } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Printer/Printer.cs b/src/Agent/Insight.Agent.Assets/Messages/Printer/Printer.cs deleted file mode 100644 index 0478fc0..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Printer/Printer.cs +++ /dev/null @@ -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, IAgentMessage { } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Processor/Processor.cs b/src/Agent/Insight.Agent.Assets/Messages/Processor/Processor.cs deleted file mode 100644 index edd63af..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Processor/Processor.cs +++ /dev/null @@ -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, IAgentMessage { } - - [MemoryPackable] - public partial class ProcessorMetric : IAgentMessage - { - [MemoryPackOrder(0)] - public DateTime? Timestamp { get; set; } - - [MemoryPackOrder(1)] - public float? ProcessorUsagePercentage { get; set; } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Service/Service.cs b/src/Agent/Insight.Agent.Assets/Messages/Service/Service.cs deleted file mode 100644 index 61aa86d..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Service/Service.cs +++ /dev/null @@ -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, IAgentMessage { } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Session/Session.cs b/src/Agent/Insight.Agent.Assets/Messages/Session/Session.cs deleted file mode 100644 index 625c4ef..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Session/Session.cs +++ /dev/null @@ -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, IAgentMessage { } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Status/Status.cs b/src/Agent/Insight.Agent.Assets/Messages/Status/Status.cs deleted file mode 100644 index de31591..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Status/Status.cs +++ /dev/null @@ -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; } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/StoragePool/StoragePool.cs b/src/Agent/Insight.Agent.Assets/Messages/StoragePool/StoragePool.cs deleted file mode 100644 index 6148979..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/StoragePool/StoragePool.cs +++ /dev/null @@ -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? 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? PhysicalDisks { get; set; } - - [MemoryPackOrder(14)] - public List? 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, 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? States { get; set; } - - [MemoryPackOrder(8)] - public HealthState? Health { get; set; } - - [MemoryPackOrder(9)] - public List? 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? 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 - } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/SystemInfo/SystemInfo.cs b/src/Agent/Insight.Agent.Assets/Messages/SystemInfo/SystemInfo.cs deleted file mode 100644 index 8ec0441..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/SystemInfo/SystemInfo.cs +++ /dev/null @@ -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; } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Trap/Trap.cs b/src/Agent/Insight.Agent.Assets/Messages/Trap/Trap.cs deleted file mode 100644 index d0a66db..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Trap/Trap.cs +++ /dev/null @@ -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>? Data { get; set; } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Update/Update.cs b/src/Agent/Insight.Agent.Assets/Messages/Update/Update.cs deleted file mode 100644 index ecc84c1..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Update/Update.cs +++ /dev/null @@ -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? Installed { get; set; } - - [MemoryPackOrder(1)] - public List? Pending { get; set; } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/User/User.cs b/src/Agent/Insight.Agent.Assets/Messages/User/User.cs deleted file mode 100644 index 968c4bb..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/User/User.cs +++ /dev/null @@ -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? Groups { get; set; } - } - - [MemoryPackable(GenerateType.Collection)] - public partial class UserList : List, 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; } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/Videocard/Videocard.cs b/src/Agent/Insight.Agent.Assets/Messages/Videocard/Videocard.cs deleted file mode 100644 index 151d441..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/Videocard/Videocard.cs +++ /dev/null @@ -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, IAgentMessage { } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent.Assets/Messages/VirtualMaschine/VirtualMaschine.cs b/src/Agent/Insight.Agent.Assets/Messages/VirtualMaschine/VirtualMaschine.cs deleted file mode 100644 index a91dc44..0000000 --- a/src/Agent/Insight.Agent.Assets/Messages/VirtualMaschine/VirtualMaschine.cs +++ /dev/null @@ -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? 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, 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? 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 - } - } -} \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Insight.Agent.csproj b/src/Agent/Insight.Agent/Insight.Agent.csproj index 59ff570..fbcdb18 100644 --- a/src/Agent/Insight.Agent/Insight.Agent.csproj +++ b/src/Agent/Insight.Agent/Insight.Agent.csproj @@ -6,7 +6,7 @@ Insight.Agent Insight agent - 2023.9.14.0 + 2023.9.21.0 enable enable @@ -27,10 +27,11 @@ + - + diff --git a/src/Agent/Insight.Agent.Assets/Models/Config.cs b/src/Agent/Insight.Agent/Models/Config.cs similarity index 100% rename from src/Agent/Insight.Agent.Assets/Models/Config.cs rename to src/Agent/Insight.Agent/Models/Config.cs diff --git a/src/Agent/Insight.Agent/Network/AgentSession.cs b/src/Agent/Insight.Agent/Network/AgentSession.cs index 84678ea..2fcd017 100644 --- a/src/Agent/Insight.Agent/Network/AgentSession.cs +++ b/src/Agent/Insight.Agent/Network/AgentSession.cs @@ -1,57 +1,56 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; using Microsoft.Extensions.Logging; using Vaitr.Network; -namespace Insight.Agent.Network +namespace Insight.Agent.Network; + +public class AgentSession : TcpSession { - public class AgentSession : TcpSession + private readonly IEnumerable> _handlers; + + public AgentSession(IEnumerable> handlers, ISerializer serializer, ILogger logger) : base(serializer, logger) { - private readonly IEnumerable> _handlers; + _handlers = handlers; + } - public AgentSession(IEnumerable> handlers, ISerializer serializer, ILogger logger) : base(serializer, logger) + protected override ValueTask OnConnectedAsync(CancellationToken cancellationToken) + { + _logger.LogInformation("Agent ({ep?}) connected", RemoteEndPoint); + return default; + } + + protected override ValueTask OnDisconnectedAsync(CancellationToken cancellationToken) + { + _logger.LogInformation("Agent ({ep?}) disconnected", RemoteEndPoint); + return default; + } + + protected override ValueTask OnSentAsync(IPacketContext context, CancellationToken cancellationToken) + { + return base.OnSentAsync(context, cancellationToken); + } + + protected override async ValueTask OnReceivedAsync(IPacketContext context, CancellationToken cancellationToken) + { + await base.OnReceivedAsync(context, cancellationToken); + + foreach (var handler in _handlers) { - _handlers = handlers; - } - - protected override ValueTask OnConnectedAsync(CancellationToken cancellationToken) - { - _logger.LogInformation("Agent ({ep?}) connected", RemoteEndPoint); - return default; - } - - protected override ValueTask OnDisconnectedAsync(CancellationToken cancellationToken) - { - _logger.LogInformation("Agent ({ep?}) disconnected", RemoteEndPoint); - return default; - } - - protected override ValueTask OnSentAsync(IPacketContext context, CancellationToken cancellationToken) - { - return base.OnSentAsync(context, cancellationToken); - } - - protected override async ValueTask OnReceivedAsync(IPacketContext context, CancellationToken cancellationToken) - { - await base.OnReceivedAsync(context, cancellationToken); - - foreach (var handler in _handlers) + try { - try - { - await handler.HandleAsync(this, context.Packet, cancellationToken); - } - catch (Exception ex) - { - _logger.LogWarning("Agent ({ep?}) {ex}", RemoteEndPoint, ex.ToString()); - } + await handler.HandleAsync(this, context.Packet, cancellationToken); + } + catch (Exception ex) + { + _logger.LogWarning("Agent ({ep?}) {ex}", RemoteEndPoint, ex.ToString()); } } + } - protected override ValueTask OnHeartbeatAsync(CancellationToken cancellationToken) - { - _logger.LogInformation("Agent ({ep?}) Heartbeat", RemoteEndPoint); - return default; - } + protected override ValueTask OnHeartbeatAsync(CancellationToken cancellationToken) + { + _logger.LogInformation("Agent ({ep?}) Heartbeat", RemoteEndPoint); + return default; } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/AuthenticationHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/AuthenticationHandler.cs index 4247693..027b0c2 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/AuthenticationHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/AuthenticationHandler.cs @@ -1,38 +1,38 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; -using Insight.Agent.Models; +using Insight.Agent.Models; using Insight.Agent.Services; using Insight.Domain.Constants; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +public class AuthenticationHandler : IMessageHandler { - public class AuthenticationHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is AuthenticationRequest) { - if (message is AuthenticationRequest) + Config? config = null; + + try { - Config? config = null; - - try - { - config = await Configurator.ReadAsync(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); + config = await Configurator.ReadAsync(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); } } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/ConsoleHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/ConsoleHandler.cs index 267bb5d..71097df 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/ConsoleHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/ConsoleHandler.cs @@ -1,13 +1,14 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management.Automation; using System.Management.Automation.Runspaces; namespace Insight.Agent.Network.Handlers; -public class ConsoleHandler : IAgentMessageHandler +public class ConsoleHandler : IMessageHandler { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { if (message is ConsoleQueryRequest consoleQueryRequest) { diff --git a/src/Agent/Insight.Agent/Network/Handlers/DriveHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/DriveHandler.cs index 13fafe8..14dba70 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/DriveHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/DriveHandler.cs @@ -1,178 +1,178 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management; using System.Runtime.Versioning; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class DriveHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class DriveHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - var result = new DriveList(); - result.AddRange(GetDrives()); + var result = new DriveList(); + result.AddRange(GetDrives()); - await sender.SendAsync(result, cancellationToken); - } - } - - private static List GetDrives() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select index, name, caption, model, manufacturer, serialNumber, size, status, interfacetype, firmwarerevision, deviceid, pnpdeviceid from win32_diskdrive") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_diskdrive"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var drives = new List(); - - using (collection) - { - foreach (ManagementObject @object in collection.Cast()) - { - var drive = new Drive(); - - var properties = @object.GetPropertyHashes(); - - drive.Index = @object.GetValue(properties, "index"); - drive.Id = @object.GetValue(properties, "deviceid")?.Trim(); - drive.Name = @object.GetValue(properties, "model")?.Trim(); - drive.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); - drive.SerialNumber = @object.GetValue(properties, "serialnumber")?.Trim(); - drive.Size = @object.GetValue(properties, "size"); - drive.Status = @object.GetValue(properties, "status")?.Trim(); - drive.InterfaceType = @object.GetValue(properties, "interfacetype")?.Trim(); - drive.FirmwareRevision = @object.GetValue(properties, "firmwarerevision")?.Trim(); - drive.PNPDeviceID = @object.GetValue(properties, "pnpdeviceid")?.Trim(); - drive.Volumes = new List(); - - var diskpartition = @object.GetRelated("win32_diskpartition"); - using (diskpartition) - { - foreach (ManagementObject dp in diskpartition.Cast()) - { - var volume = new Volume(); - var dpProperties = dp.GetPropertyHashes(); - - volume.NumberOfBlocks = dp.GetValue(dpProperties, "numberofblocks"); - volume.BootPartition = dp.GetValue(dpProperties, "bootpartition"); - volume.PrimaryPartition = dp.GetValue(dpProperties, "primarypartition"); - volume.Size = dp.GetValue(dpProperties, "size"); - volume.Index = dp.GetValue(dpProperties, "index"); - volume.Type = dp.GetValue(dpProperties, "type")?.Trim(); - volume.Bootable = dp.GetValue(dpProperties, "bootable"); - volume.BlockSize = dp.GetValue(dpProperties, "blocksize"); - volume.StartingOffset = dp.GetValue(dpProperties, "startingoffset"); - - var logicaldisk = dp.GetRelated("win32_logicaldisk"); - using (logicaldisk) - { - foreach (ManagementObject ld in logicaldisk.Cast()) - { - var ldProperties = ld.GetPropertyHashes(); - - volume.Id = ld.GetValue(ldProperties, "deviceid")?.Trim(); - volume.Name = ld.GetValue(ldProperties, "volumename")?.Trim(); - volume.SerialNumber = ld.GetValue(ldProperties, "volumeserialnumber")?.Trim(); - volume.DriveType = (DriveType)ld.GetValue(ldProperties, "drivetype"); - volume.FileSystem = ld.GetValue(ldProperties, "filesystem")?.Trim(); - volume.Compressed = ld.GetValue(ldProperties, "compressed"); - volume.Size = ld.GetValue(ldProperties, "size"); - volume.FreeSpace = ld.GetValue(ldProperties, "freespace"); - volume.ProviderName = ld.GetValue(ldProperties, "providername")?.Trim(); - } - } - - drive.Volumes.Add(volume); - } - } - - drives.Add(drive); - } - } - - return drives; - } - - private static List GetVolumes() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select deviceid, volumename, volumeserialnumber, drivetype, filesystem, compressed, size, freeSpace, providername from win32_logicaldisk") - }; - - // per device query - // "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + driveDeviceId + "'} WHERE AssocClass=Win32_DiskDriveToDiskPartition" - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_logicaldisk"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var volumes = new List(); - - using (collection) - { - foreach (ManagementObject @object in collection.Cast()) - { - var volume = new Volume(); - - var properties = @object.GetPropertyHashes(); - - //volume.DeviceId = @object.GetValue(properties, "deviceid")?.Trim(); - //volume.VolumeName = @object.GetValue(properties, "volumename")?.Trim(); - //volume.VolumeSerialNumber = @object.GetValue(properties, "volumeserialnumber")?.Trim(); - volume.DriveType = (DriveType)@object.GetValue(properties, "drivetype"); - volume.FileSystem = @object.GetValue(properties, "filesystem")?.Trim(); - volume.Compressed = @object.GetValue(properties, "compressed"); - volume.Size = @object.GetValue(properties, "size"); - volume.FreeSpace = @object.GetValue(properties, "freespace"); - volume.ProviderName = @object.GetValue(properties, "providername")?.Trim(); - - if (volume.Id is not null) - { - searcher.Query = new ObjectQuery("associators of {win32_logicaldisk.deviceid='" + volume.Id + "'} where assocclass=win32_logicaldisktopartition"); - - if (searcher.TryGet(out var collection2)) - { - using (collection2) - { - foreach (ManagementObject @object2 in collection2) - { - var properties2 = @object2.GetPropertyHashes(); - - volume.Index = @object2.GetValue(properties2, "index"); - //volume.DiskIndex = @object2.GetValue(properties2, "diskindex"); - volume.Type = @object2.GetValue(properties2, "type")?.Trim(); - volume.Bootable = @object2.GetValue(properties2, "bootable"); - volume.PrimaryPartition = @object2.GetValue(properties2, "primarypartition"); - volume.BootPartition = @object2.GetValue(properties2, "bootpartition"); - volume.BlockSize = @object2.GetValue(properties2, "blocksize"); - volume.NumberOfBlocks = @object2.GetValue(properties2, "numberofblocks"); - volume.StartingOffset = @object2.GetValue(properties2, "startingoffset"); - } - } - } - } - - volumes.Add(volume); - } - } - - return volumes; + await sender.SendAsync(result, cancellationToken); } } + + private static List GetDrives() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select index, name, caption, model, manufacturer, serialNumber, size, status, interfacetype, firmwarerevision, deviceid, pnpdeviceid from win32_diskdrive") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_diskdrive"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var drives = new List(); + + using (collection) + { + foreach (ManagementObject @object in collection.Cast()) + { + var drive = new Drive(); + + var properties = @object.GetPropertyHashes(); + + drive.Index = @object.GetValue(properties, "index"); + drive.Id = @object.GetValue(properties, "deviceid")?.Trim(); + drive.Name = @object.GetValue(properties, "model")?.Trim(); + drive.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); + drive.SerialNumber = @object.GetValue(properties, "serialnumber")?.Trim(); + drive.Size = @object.GetValue(properties, "size"); + drive.Status = @object.GetValue(properties, "status")?.Trim(); + drive.InterfaceType = @object.GetValue(properties, "interfacetype")?.Trim(); + drive.FirmwareRevision = @object.GetValue(properties, "firmwarerevision")?.Trim(); + drive.PNPDeviceID = @object.GetValue(properties, "pnpdeviceid")?.Trim(); + drive.Volumes = new List(); + + var diskpartition = @object.GetRelated("win32_diskpartition"); + using (diskpartition) + { + foreach (ManagementObject dp in diskpartition.Cast()) + { + var volume = new Volume(); + var dpProperties = dp.GetPropertyHashes(); + + volume.NumberOfBlocks = dp.GetValue(dpProperties, "numberofblocks"); + volume.BootPartition = dp.GetValue(dpProperties, "bootpartition"); + volume.PrimaryPartition = dp.GetValue(dpProperties, "primarypartition"); + volume.Size = dp.GetValue(dpProperties, "size"); + volume.Index = dp.GetValue(dpProperties, "index"); + volume.Type = dp.GetValue(dpProperties, "type")?.Trim(); + volume.Bootable = dp.GetValue(dpProperties, "bootable"); + volume.BlockSize = dp.GetValue(dpProperties, "blocksize"); + volume.StartingOffset = dp.GetValue(dpProperties, "startingoffset"); + + var logicaldisk = dp.GetRelated("win32_logicaldisk"); + using (logicaldisk) + { + foreach (ManagementObject ld in logicaldisk.Cast()) + { + var ldProperties = ld.GetPropertyHashes(); + + volume.Id = ld.GetValue(ldProperties, "deviceid")?.Trim(); + volume.Name = ld.GetValue(ldProperties, "volumename")?.Trim(); + volume.SerialNumber = ld.GetValue(ldProperties, "volumeserialnumber")?.Trim(); + volume.DriveType = (DriveType)ld.GetValue(ldProperties, "drivetype"); + volume.FileSystem = ld.GetValue(ldProperties, "filesystem")?.Trim(); + volume.Compressed = ld.GetValue(ldProperties, "compressed"); + volume.Size = ld.GetValue(ldProperties, "size"); + volume.FreeSpace = ld.GetValue(ldProperties, "freespace"); + volume.ProviderName = ld.GetValue(ldProperties, "providername")?.Trim(); + } + } + + drive.Volumes.Add(volume); + } + } + + drives.Add(drive); + } + } + + return drives; + } + + private static List GetVolumes() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select deviceid, volumename, volumeserialnumber, drivetype, filesystem, compressed, size, freeSpace, providername from win32_logicaldisk") + }; + + // per device query + // "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + driveDeviceId + "'} WHERE AssocClass=Win32_DiskDriveToDiskPartition" + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_logicaldisk"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var volumes = new List(); + + using (collection) + { + foreach (ManagementObject @object in collection.Cast()) + { + var volume = new Volume(); + + var properties = @object.GetPropertyHashes(); + + //volume.DeviceId = @object.GetValue(properties, "deviceid")?.Trim(); + //volume.VolumeName = @object.GetValue(properties, "volumename")?.Trim(); + //volume.VolumeSerialNumber = @object.GetValue(properties, "volumeserialnumber")?.Trim(); + volume.DriveType = (DriveType)@object.GetValue(properties, "drivetype"); + volume.FileSystem = @object.GetValue(properties, "filesystem")?.Trim(); + volume.Compressed = @object.GetValue(properties, "compressed"); + volume.Size = @object.GetValue(properties, "size"); + volume.FreeSpace = @object.GetValue(properties, "freespace"); + volume.ProviderName = @object.GetValue(properties, "providername")?.Trim(); + + if (volume.Id is not null) + { + searcher.Query = new ObjectQuery("associators of {win32_logicaldisk.deviceid='" + volume.Id + "'} where assocclass=win32_logicaldisktopartition"); + + if (searcher.TryGet(out var collection2)) + { + using (collection2) + { + foreach (ManagementObject @object2 in collection2) + { + var properties2 = @object2.GetPropertyHashes(); + + volume.Index = @object2.GetValue(properties2, "index"); + //volume.DiskIndex = @object2.GetValue(properties2, "diskindex"); + volume.Type = @object2.GetValue(properties2, "type")?.Trim(); + volume.Bootable = @object2.GetValue(properties2, "bootable"); + volume.PrimaryPartition = @object2.GetValue(properties2, "primarypartition"); + volume.BootPartition = @object2.GetValue(properties2, "bootpartition"); + volume.BlockSize = @object2.GetValue(properties2, "blocksize"); + volume.NumberOfBlocks = @object2.GetValue(properties2, "numberofblocks"); + volume.StartingOffset = @object2.GetValue(properties2, "startingoffset"); + } + } + } + } + + volumes.Add(volume); + } + } + + return volumes; + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/InterfaceHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/InterfaceHandler.cs index 2d6e294..b910c16 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/InterfaceHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/InterfaceHandler.cs @@ -1,274 +1,274 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management; using System.Net; using System.Net.NetworkInformation; using System.Runtime.InteropServices; using System.Runtime.Versioning; -using Route = Insight.Agent.Messages.Route; +using Route = Insight.Domain.Messages.Agent.Route; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class InterfaceHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class InterfaceHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - var result = new InterfaceList(); - result.AddRange(GetInterfaces()); + var result = new InterfaceList(); + result.AddRange(GetInterfaces()); - await sender.SendAsync(result, cancellationToken); - } - } - - private static List GetInterfaces() - { - if (NetworkInterface.GetIsNetworkAvailable() is false) return null; - if (NetworkInterface.GetAllNetworkInterfaces().Any() is false) return null; - - var interfaces = new List(); - - foreach (var ni in NetworkInterface.GetAllNetworkInterfaces()) - { - var ipProperties = ni.GetIPProperties(); - var ipStatistics = ni.GetIPStatistics(); - - var @interface = new Interface - { - Mac = ni.GetPhysicalAddress().ToString(), - Name = ni.Name, - Description = ni.Description, - Type = ni.NetworkInterfaceType, - Speed = ni.Speed, - Status = ni.OperationalStatus, - Suffix = ipProperties.DnsSuffix, - Sent = ipStatistics.BytesSent, - Received = ipStatistics.BytesReceived, - IncomingPacketsDiscarded = ipStatistics.IncomingPacketsDiscarded, - IncomingPacketsWithErrors = ipStatistics.IncomingPacketsWithErrors, - IncomingUnknownProtocolPackets = ipStatistics.IncomingUnknownProtocolPackets, - OutgoingPacketsDiscarded = ipStatistics.OutgoingPacketsDiscarded, - OutgoingPacketsWithErrors = ipStatistics.OutgoingPacketsWithErrors - }; - - try - { - var propertiesV4 = ipProperties.GetIPv4Properties(); - @interface.Index = uint.Parse(propertiesV4.Index.ToString()); - @interface.Ipv4Mtu = propertiesV4.Mtu; - @interface.Ipv4Dhcp = propertiesV4.IsDhcpEnabled; - @interface.Ipv4Forwarding = propertiesV4.IsForwardingEnabled; - } - catch (Exception) { } - - try - { - var propertiesV6 = ipProperties.GetIPv6Properties(); - @interface.Index = uint.Parse(propertiesV6.Index.ToString()); - @interface.Ipv6Mtu = propertiesV6.Mtu; - } - catch (Exception) { } - - @interface.Gateways = GetAddresses(ipProperties.GatewayAddresses); - @interface.Addresses = GetAddresses(ipProperties.UnicastAddresses); - @interface.Dns = GetAddresses(ipProperties.DnsAddresses); - @interface.Dhcp = GetAddresses(ipProperties.DhcpServerAddresses); - - if (@interface.Index.HasValue) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery($"select interfaceindex, guid, physicaladapter, manufacturer from win32_networkadapter where interfaceindex = {@interface.Index}") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery($"select * from win32_networkadapter where interfaceindex = {@interface.Index}"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - using (collection) - { - foreach (ManagementObject @object in collection) - { - var properties = @object.GetPropertyHashes(); - - @interface.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); - @interface.Guid = @object.GetValue(properties, "guid"); - @interface.Physical = @object.GetValue(properties, "physicaladapter"); - - break; - } - } - - @interface.Routes = QueryInterfaceRoutes(@interface.Index.Value); - } - } - - interfaces.Add(@interface); - } - - return interfaces; - } - - private static List QueryInterfaceRoutes(uint interfaceIndex) - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\standardcimv2"), - Query = new ObjectQuery($"select addressFamily, state, interfaceindex, routemetric, nexthop, destinationprefix from msft_netroute where interfaceindex = {interfaceIndex}") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery($"select * from msft_netroute where interfaceindex = {interfaceIndex}"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var routes = new List(); - - using (collection) - { - foreach (var @object in collection) - { - var route = new Route - { - InterfaceIndex = interfaceIndex - }; - - var properties = @object.GetPropertyHashes(); - - if (@object.TryGetValue(properties, "routemetric", out var routemetric)) - { - if (int.TryParse(routemetric?.ToString(), out var metric)) route.Metric = metric; - } - - if (@object.TryGetValue(properties, "nexthop", out var nexthop)) - { - if (IPAddress.TryParse(nexthop?.ToString(), out var gateway)) route.Gateway = new IPAddress2(gateway); - } - - if (@object.TryGetValue(properties, "destinationprefix", out var destinationprefix)) - { - var split = destinationprefix?.ToString()?.Split('/'); - var cidrData = split?[1]; - - if (IPAddress.TryParse(split?[0], out var destination)) - route.Destination = new IPAddress2(destination); - - if (int.TryParse(cidrData, out var cidr)) - { - var mask = ConvertCidr(cidr); - route.Mask = mask; - } - } - - routes.Add(route); - } - } - - return routes; - } - - private static List GetAddresses(UnicastIPAddressInformationCollection unicastCollection) - { - var addresses = new List(); - - if (unicastCollection.Any() is false) return addresses; - - foreach (var unicast in unicastCollection) - { - addresses.Add(new Unicast - { - IpAddress = new IPAddress2(unicast.Address), - AddressPreferredLifetime = unicast.AddressPreferredLifetime, - AddressValidLifetime = unicast.AddressValidLifetime, - DuplicateAddressDetectionState = unicast.DuplicateAddressDetectionState, - Ipv4Mask = new IPAddress2(unicast.IPv4Mask), - PrefixLength = unicast.PrefixLength, - PrefixOrigin = unicast.PrefixOrigin, - SuffixOrigin = unicast.SuffixOrigin, - DhcpLeaseLifetime = unicast.DhcpLeaseLifetime, - }); - } - - return addresses; - } - - private static List GetAddresses(IPAddressCollection addressCollection) - { - var addresses = new List(); - - if (addressCollection.Any() is false) return addresses; - - foreach (var address in addressCollection) - { - addresses.Add(new IPAddress2(address)); - } - - return addresses; - } - - private static List GetAddresses(GatewayIPAddressInformationCollection addressCollection) - { - var addresses = new List(); - - if (addressCollection.Any() is false) return addresses; - - foreach (var address in addressCollection) - { - addresses.Add(new IPAddress2(address.Address)); - } - - return addresses; - } - - private static string? ConvertCidr(int cidr) - { - return cidr switch - { - 0 => "0.0.0.0", - 1 => "128.0.0.0", - 2 => "192.0.0.0", - 3 => "224.0.0.0", - 4 => "240.0.0.0", - 5 => "248.0.0.0", - 6 => "252.0.0.0", - 7 => "254.0.0.0", - 8 => "255.0.0.0", - 9 => "255.128.0.0", - 10 => "255.192.0.0", - 11 => "255.224.0.0", - 12 => "255.240.0.0", - 13 => "255.248.0.0", - 14 => "255.252.0.0", - 15 => "255.254.0.0", - 16 => "255.255.0.0", - 17 => "255.255.128.0", - 18 => "255.255.192.0", - 19 => "255.255.224.0", - 20 => "255.255.240.0", - 21 => "255.255.248.0", - 22 => "255.255.252.0", - 23 => "255.255.254.0", - 24 => "255.255.255.0", - 25 => "255.255.255.128", - 26 => "255.255.255.192", - 27 => "255.255.255.224", - 28 => "255.255.255.240", - 29 => "255.255.255.248", - 30 => "255.255.255.252", - 31 => "255.255.255.254", - 32 => "255.255.255.255", - _ => null, - }; + await sender.SendAsync(result, cancellationToken); } } + + private static List GetInterfaces() + { + if (NetworkInterface.GetIsNetworkAvailable() is false) return null; + if (NetworkInterface.GetAllNetworkInterfaces().Any() is false) return null; + + var interfaces = new List(); + + foreach (var ni in NetworkInterface.GetAllNetworkInterfaces()) + { + var ipProperties = ni.GetIPProperties(); + var ipStatistics = ni.GetIPStatistics(); + + var @interface = new Interface + { + Mac = ni.GetPhysicalAddress().ToString(), + Name = ni.Name, + Description = ni.Description, + Type = ni.NetworkInterfaceType, + Speed = ni.Speed, + Status = ni.OperationalStatus, + Suffix = ipProperties.DnsSuffix, + Sent = ipStatistics.BytesSent, + Received = ipStatistics.BytesReceived, + IncomingPacketsDiscarded = ipStatistics.IncomingPacketsDiscarded, + IncomingPacketsWithErrors = ipStatistics.IncomingPacketsWithErrors, + IncomingUnknownProtocolPackets = ipStatistics.IncomingUnknownProtocolPackets, + OutgoingPacketsDiscarded = ipStatistics.OutgoingPacketsDiscarded, + OutgoingPacketsWithErrors = ipStatistics.OutgoingPacketsWithErrors + }; + + try + { + var propertiesV4 = ipProperties.GetIPv4Properties(); + @interface.Index = uint.Parse(propertiesV4.Index.ToString()); + @interface.Ipv4Mtu = propertiesV4.Mtu; + @interface.Ipv4Dhcp = propertiesV4.IsDhcpEnabled; + @interface.Ipv4Forwarding = propertiesV4.IsForwardingEnabled; + } + catch (Exception) { } + + try + { + var propertiesV6 = ipProperties.GetIPv6Properties(); + @interface.Index = uint.Parse(propertiesV6.Index.ToString()); + @interface.Ipv6Mtu = propertiesV6.Mtu; + } + catch (Exception) { } + + @interface.Gateways = GetAddresses(ipProperties.GatewayAddresses); + @interface.Addresses = GetAddresses(ipProperties.UnicastAddresses); + @interface.Dns = GetAddresses(ipProperties.DnsAddresses); + @interface.Dhcp = GetAddresses(ipProperties.DhcpServerAddresses); + + if (@interface.Index.HasValue) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery($"select interfaceindex, guid, physicaladapter, manufacturer from win32_networkadapter where interfaceindex = {@interface.Index}") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery($"select * from win32_networkadapter where interfaceindex = {@interface.Index}"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + using (collection) + { + foreach (ManagementObject @object in collection) + { + var properties = @object.GetPropertyHashes(); + + @interface.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); + @interface.Guid = @object.GetValue(properties, "guid"); + @interface.Physical = @object.GetValue(properties, "physicaladapter"); + + break; + } + } + + @interface.Routes = QueryInterfaceRoutes(@interface.Index.Value); + } + } + + interfaces.Add(@interface); + } + + return interfaces; + } + + private static List QueryInterfaceRoutes(uint interfaceIndex) + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\standardcimv2"), + Query = new ObjectQuery($"select addressFamily, state, interfaceindex, routemetric, nexthop, destinationprefix from msft_netroute where interfaceindex = {interfaceIndex}") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery($"select * from msft_netroute where interfaceindex = {interfaceIndex}"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var routes = new List(); + + using (collection) + { + foreach (var @object in collection) + { + var route = new Route + { + InterfaceIndex = interfaceIndex + }; + + var properties = @object.GetPropertyHashes(); + + if (@object.TryGetValue(properties, "routemetric", out var routemetric)) + { + if (int.TryParse(routemetric?.ToString(), out var metric)) route.Metric = metric; + } + + if (@object.TryGetValue(properties, "nexthop", out var nexthop)) + { + if (IPAddress.TryParse(nexthop?.ToString(), out var gateway)) route.Gateway = new IPAddress2(gateway); + } + + if (@object.TryGetValue(properties, "destinationprefix", out var destinationprefix)) + { + var split = destinationprefix?.ToString()?.Split('/'); + var cidrData = split?[1]; + + if (IPAddress.TryParse(split?[0], out var destination)) + route.Destination = new IPAddress2(destination); + + if (int.TryParse(cidrData, out var cidr)) + { + var mask = ConvertCidr(cidr); + route.Mask = mask; + } + } + + routes.Add(route); + } + } + + return routes; + } + + private static List GetAddresses(UnicastIPAddressInformationCollection unicastCollection) + { + var addresses = new List(); + + if (unicastCollection.Any() is false) return addresses; + + foreach (var unicast in unicastCollection) + { + addresses.Add(new Unicast + { + IpAddress = new IPAddress2(unicast.Address), + AddressPreferredLifetime = unicast.AddressPreferredLifetime, + AddressValidLifetime = unicast.AddressValidLifetime, + DuplicateAddressDetectionState = unicast.DuplicateAddressDetectionState, + Ipv4Mask = new IPAddress2(unicast.IPv4Mask), + PrefixLength = unicast.PrefixLength, + PrefixOrigin = unicast.PrefixOrigin, + SuffixOrigin = unicast.SuffixOrigin, + DhcpLeaseLifetime = unicast.DhcpLeaseLifetime, + }); + } + + return addresses; + } + + private static List GetAddresses(IPAddressCollection addressCollection) + { + var addresses = new List(); + + if (addressCollection.Any() is false) return addresses; + + foreach (var address in addressCollection) + { + addresses.Add(new IPAddress2(address)); + } + + return addresses; + } + + private static List GetAddresses(GatewayIPAddressInformationCollection addressCollection) + { + var addresses = new List(); + + if (addressCollection.Any() is false) return addresses; + + foreach (var address in addressCollection) + { + addresses.Add(new IPAddress2(address.Address)); + } + + return addresses; + } + + private static string? ConvertCidr(int cidr) + { + return cidr switch + { + 0 => "0.0.0.0", + 1 => "128.0.0.0", + 2 => "192.0.0.0", + 3 => "224.0.0.0", + 4 => "240.0.0.0", + 5 => "248.0.0.0", + 6 => "252.0.0.0", + 7 => "254.0.0.0", + 8 => "255.0.0.0", + 9 => "255.128.0.0", + 10 => "255.192.0.0", + 11 => "255.224.0.0", + 12 => "255.240.0.0", + 13 => "255.248.0.0", + 14 => "255.252.0.0", + 15 => "255.254.0.0", + 16 => "255.255.0.0", + 17 => "255.255.128.0", + 18 => "255.255.192.0", + 19 => "255.255.224.0", + 20 => "255.255.240.0", + 21 => "255.255.248.0", + 22 => "255.255.252.0", + 23 => "255.255.254.0", + 24 => "255.255.255.0", + 25 => "255.255.255.128", + 26 => "255.255.255.192", + 27 => "255.255.255.224", + 28 => "255.255.255.240", + 29 => "255.255.255.248", + 30 => "255.255.255.252", + 31 => "255.255.255.254", + 32 => "255.255.255.255", + _ => null, + }; + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/MainboardHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/MainboardHandler.cs index 43f210b..0c80c47 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/MainboardHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/MainboardHandler.cs @@ -1,86 +1,86 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management; using System.Runtime.Versioning; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class MainboardHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class MainboardHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - await sender.SendAsync(GetMainboard(), cancellationToken); - } - } - - private static Mainboard GetMainboard() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select manufacturer, product, serialnumber from win32_baseboard") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_baseboard"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var mainboard = new Mainboard(); - - using (collection) - { - foreach (ManagementObject @object in collection.Cast()) - { - var properties = @object.GetPropertyHashes(); - - mainboard.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); - mainboard.Model = @object.GetValue(properties, "product")?.Trim(); - mainboard.Serial = @object.GetValue(properties, "serialnumber")?.Trim(); - - break; - } - } - - searcher.Query = new ObjectQuery("select manufacturer, serialnumber, smbiosbiosversion, releasedate from win32_bios"); - - if (searcher.TryGet(out var collection2) is false) - { - searcher.Query = new ObjectQuery("select * from win32_bios"); - - if (searcher.TryGet(out collection2) is false) return null; - } - - using (collection2) - { - foreach (ManagementObject @object in collection2.Cast()) - { - var properties = @object.GetPropertyHashes(); - - mainboard.BiosManufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); - mainboard.Serial = @object.GetValue(properties, "serialnumber")?.Trim(); - mainboard.BiosVersion = @object.GetValue(properties, "smbiosbiosversion")?.Trim(); - - if (@object.TryGetValue(properties, "releasedate", out var releasedate)) - { - mainboard.BiosDate = ManagementDateTimeConverter.ToDateTime(releasedate?.ToString()); - } - - break; - } - } - - //Logger.LogWarning(JsonSerializer.Serialize(mainboard, new JsonSerializerOptions - //{ - // WriteIndented= true - //})); - - return mainboard; + await sender.SendAsync(GetMainboard(), cancellationToken); } } + + private static Mainboard GetMainboard() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select manufacturer, product, serialnumber from win32_baseboard") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_baseboard"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var mainboard = new Mainboard(); + + using (collection) + { + foreach (ManagementObject @object in collection.Cast()) + { + var properties = @object.GetPropertyHashes(); + + mainboard.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); + mainboard.Model = @object.GetValue(properties, "product")?.Trim(); + mainboard.Serial = @object.GetValue(properties, "serialnumber")?.Trim(); + + break; + } + } + + searcher.Query = new ObjectQuery("select manufacturer, serialnumber, smbiosbiosversion, releasedate from win32_bios"); + + if (searcher.TryGet(out var collection2) is false) + { + searcher.Query = new ObjectQuery("select * from win32_bios"); + + if (searcher.TryGet(out collection2) is false) return null; + } + + using (collection2) + { + foreach (ManagementObject @object in collection2.Cast()) + { + var properties = @object.GetPropertyHashes(); + + mainboard.BiosManufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); + mainboard.Serial = @object.GetValue(properties, "serialnumber")?.Trim(); + mainboard.BiosVersion = @object.GetValue(properties, "smbiosbiosversion")?.Trim(); + + if (@object.TryGetValue(properties, "releasedate", out var releasedate)) + { + mainboard.BiosDate = ManagementDateTimeConverter.ToDateTime(releasedate?.ToString()); + } + + break; + } + } + + //Logger.LogWarning(JsonSerializer.Serialize(mainboard, new JsonSerializerOptions + //{ + // WriteIndented= true + //})); + + return mainboard; + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/MemoryHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/MemoryHandler.cs index 11ef77f..34f0460 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/MemoryHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/MemoryHandler.cs @@ -1,123 +1,123 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management; using System.Runtime.Versioning; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class MemoryHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class MemoryHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - var result = new MemoryList(); - result.AddRange(GetMemory()); + var result = new MemoryList(); + result.AddRange(GetMemory()); - await sender.SendAsync(result, cancellationToken); - } + await sender.SendAsync(result, cancellationToken); } - - private static List GetMemory() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select tag, devicelocator, manufacturer, partnumber, serialnumber, capacity, speed, maxvoltage, configuredclockspeed, configuredvoltage from win32_physicalmemory") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_physicalmemory"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var memorysticks = new List(); - - using (collection) - { - uint index = 0; - - foreach (ManagementObject @object in collection.Cast()) - { - var @memory = new Memory(); - - var properties = @object.GetPropertyHashes(); - - @memory.Index = index; - @memory.Tag = @object.GetValue(properties, "tag")?.Trim(); - @memory.Location = @object.GetValue(properties, "devicelocator")?.Trim(); - @memory.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); - @memory.Model = @object.GetValue(properties, "partnumber")?.Trim(); - @memory.Serial = @object.GetValue(properties, "serialnumber")?.Trim(); - @memory.Capacity = @object.GetValue(properties, "capacity"); - @memory.Speed = @object.GetValue(properties, "speed"); - @memory.Voltage = @object.GetValue(properties, "maxvoltage"); - @memory.ConfiguredSpeed = @object.GetValue(properties, "configuredclockspeed"); - @memory.ConfiguredVoltage = @object.GetValue(properties, "configuredvoltage"); - - memorysticks.Add(@memory); - index++; - } - } - - return memorysticks; - } - - //private async ValueTask GetMemoryMetricAsync(CancellationToken cancellationToken) - //{ - // var metric = new Memory.Metric(); - - // using var searcher = new ManagementObjectSearcher - // { - // Scope = new ManagementScope(@"root\cimv2"), - // Query = new ObjectQuery("select totalphysicalmemory from win32_computersystem") - // }; - - // if (searcher.TryGet(out var collection) is false) - // { - // searcher.Query = new ObjectQuery("select * from win32_computersystem"); - - // if (searcher.TryGet(out collection) is false) return metric; - // } - - // ulong capacity = 0; - - // using (collection) - // { - // foreach (var @object in collection) - // { - // var properties = @object.GetPropertyHashes(); - - // if (@object.TryGetValue(properties, "totalphysicalmemory", out capacity)) - // { - // capacity = capacity / 1024 / 1024; - // } - - // break; - // } - // } - - // if (MemoryAvailableCounter is null) - // { - // MemoryAvailableCounter = new PerformanceCounter - // { - // CategoryName = "Memory", - // CounterName = "Available MBytes" - // }; - - // metric.MemoryAvailable = MemoryAvailableCounter.NextValue(); - // await Task.Delay(1000, cancellationToken).ConfigureAwait(false); - // } - - // metric.Timestamp = DateTime.Now; - // metric.MemoryAvailable = MemoryAvailableCounter.NextValue(); - // metric.MemoryUsed = capacity - metric.MemoryAvailable; - // metric.MemoryUsagePercentage = metric.MemoryUsed / capacity * 100; - // metric.MemoryAvailablePercentage = 100 - metric.MemoryUsagePercentage; - // return metric; - //} } + + private static List GetMemory() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select tag, devicelocator, manufacturer, partnumber, serialnumber, capacity, speed, maxvoltage, configuredclockspeed, configuredvoltage from win32_physicalmemory") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_physicalmemory"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var memorysticks = new List(); + + using (collection) + { + uint index = 0; + + foreach (ManagementObject @object in collection.Cast()) + { + var @memory = new Memory(); + + var properties = @object.GetPropertyHashes(); + + @memory.Index = index; + @memory.Tag = @object.GetValue(properties, "tag")?.Trim(); + @memory.Location = @object.GetValue(properties, "devicelocator")?.Trim(); + @memory.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); + @memory.Model = @object.GetValue(properties, "partnumber")?.Trim(); + @memory.Serial = @object.GetValue(properties, "serialnumber")?.Trim(); + @memory.Capacity = @object.GetValue(properties, "capacity"); + @memory.Speed = @object.GetValue(properties, "speed"); + @memory.Voltage = @object.GetValue(properties, "maxvoltage"); + @memory.ConfiguredSpeed = @object.GetValue(properties, "configuredclockspeed"); + @memory.ConfiguredVoltage = @object.GetValue(properties, "configuredvoltage"); + + memorysticks.Add(@memory); + index++; + } + } + + return memorysticks; + } + + //private async ValueTask GetMemoryMetricAsync(CancellationToken cancellationToken) + //{ + // var metric = new Memory.Metric(); + + // using var searcher = new ManagementObjectSearcher + // { + // Scope = new ManagementScope(@"root\cimv2"), + // Query = new ObjectQuery("select totalphysicalmemory from win32_computersystem") + // }; + + // if (searcher.TryGet(out var collection) is false) + // { + // searcher.Query = new ObjectQuery("select * from win32_computersystem"); + + // if (searcher.TryGet(out collection) is false) return metric; + // } + + // ulong capacity = 0; + + // using (collection) + // { + // foreach (var @object in collection) + // { + // var properties = @object.GetPropertyHashes(); + + // if (@object.TryGetValue(properties, "totalphysicalmemory", out capacity)) + // { + // capacity = capacity / 1024 / 1024; + // } + + // break; + // } + // } + + // if (MemoryAvailableCounter is null) + // { + // MemoryAvailableCounter = new PerformanceCounter + // { + // CategoryName = "Memory", + // CounterName = "Available MBytes" + // }; + + // metric.MemoryAvailable = MemoryAvailableCounter.NextValue(); + // await Task.Delay(1000, cancellationToken).ConfigureAwait(false); + // } + + // metric.Timestamp = DateTime.Now; + // metric.MemoryAvailable = MemoryAvailableCounter.NextValue(); + // metric.MemoryUsed = capacity - metric.MemoryAvailable; + // metric.MemoryUsagePercentage = metric.MemoryUsed / capacity * 100; + // metric.MemoryAvailablePercentage = 100 - metric.MemoryUsagePercentage; + // return metric; + //} } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/OperationSystemHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/OperationSystemHandler.cs index 0a36aad..a925804 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/OperationSystemHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/OperationSystemHandler.cs @@ -1,91 +1,91 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Microsoft.Win32; using System.Management; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.AccessControl; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class OperationSystemHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class OperationSystemHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - await sender.SendAsync(GetOperatingSystem(), cancellationToken); - } - } - - private static OperationSystem GetOperatingSystem() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select caption, version, serialnumber, osarchitecture, installdate from win32_operatingsystem") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_operatingsystem"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var os = new OperationSystem(); - - using (collection) - { - foreach (ManagementObject @object in collection) - { - var properties = @object.GetPropertyHashes(); - - os.Name = @object.GetValue(properties, "caption")?.Trim(); - os.Version = @object.GetValue(properties, "version")?.Trim(); - os.SerialNumber = @object.GetValue(properties, "serialnumber")?.Trim(); - - if (@object.TryGetValue(properties, "osarchitecture", out var architecture)) - { - if (architecture is not null && architecture.ToLower().Contains("64")) os.Architecture = Architecture.X64; - } - else - { - os.Architecture = Architecture.X86; - } - - if (@object.TryGetValue(properties, "installdate", out var installdate)) - { - os.InstallDate = ManagementDateTimeConverter.ToDateTime(installdate?.ToString()); - } - - break; - } - } - - using var registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default); - using var key = registry.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey); - - if (key is not null && key?.GetValue("UBR")?.ToString() is string buildNumber) - { - os.Version = $"{os.Version}.{buildNumber}"; - } - - searcher.Query = new ObjectQuery("select * from win32_portconnector"); - - if (searcher.TryGet(out var collection2) is false) - { - os.Virtual = true; - } - else - { - os.Virtual = false; - } - - collection2.Dispose(); - - return os; + await sender.SendAsync(GetOperatingSystem(), cancellationToken); } } + + private static OperationSystem GetOperatingSystem() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select caption, version, serialnumber, osarchitecture, installdate from win32_operatingsystem") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_operatingsystem"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var os = new OperationSystem(); + + using (collection) + { + foreach (ManagementObject @object in collection) + { + var properties = @object.GetPropertyHashes(); + + os.Name = @object.GetValue(properties, "caption")?.Trim(); + os.Version = @object.GetValue(properties, "version")?.Trim(); + os.SerialNumber = @object.GetValue(properties, "serialnumber")?.Trim(); + + if (@object.TryGetValue(properties, "osarchitecture", out var architecture)) + { + if (architecture is not null && architecture.ToLower().Contains("64")) os.Architecture = Architecture.X64; + } + else + { + os.Architecture = Architecture.X86; + } + + if (@object.TryGetValue(properties, "installdate", out var installdate)) + { + os.InstallDate = ManagementDateTimeConverter.ToDateTime(installdate?.ToString()); + } + + break; + } + } + + using var registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default); + using var key = registry.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey); + + if (key is not null && key?.GetValue("UBR")?.ToString() is string buildNumber) + { + os.Version = $"{os.Version}.{buildNumber}"; + } + + searcher.Query = new ObjectQuery("select * from win32_portconnector"); + + if (searcher.TryGet(out var collection2) is false) + { + os.Virtual = true; + } + else + { + os.Virtual = false; + } + + collection2.Dispose(); + + return os; + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/PrinterHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/PrinterHandler.cs index f52c60d..842f9ea 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/PrinterHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/PrinterHandler.cs @@ -1,60 +1,60 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management; using System.Runtime.Versioning; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class PrinterHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class PrinterHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - var result = new PrinterList(); - result.AddRange(GetPrinters()); + var result = new PrinterList(); + result.AddRange(GetPrinters()); - await sender.SendAsync(result, cancellationToken); - } - } - - private static List GetPrinters() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select drivername, name, portname, location, comment from win32_printer") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_printer"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var printers = new List(); - - using (collection) - { - foreach (ManagementObject @object in collection.Cast()) - { - var printer = new Printer(); - - var properties = @object.GetPropertyHashes(); - - printer.Driver = @object.GetValue(properties, "drivername")?.Trim(); - printer.Name = @object.GetValue(properties, "name")?.Trim(); - printer.Port = @object.GetValue(properties, "portname")?.Trim(); - printer.Location = @object.GetValue(properties, "location")?.Trim(); - printer.Comment = @object.GetValue(properties, "comment")?.Trim(); - - printers.Add(printer); - } - } - - return printers; + await sender.SendAsync(result, cancellationToken); } } + + private static List GetPrinters() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select drivername, name, portname, location, comment from win32_printer") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_printer"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var printers = new List(); + + using (collection) + { + foreach (ManagementObject @object in collection.Cast()) + { + var printer = new Printer(); + + var properties = @object.GetPropertyHashes(); + + printer.Driver = @object.GetValue(properties, "drivername")?.Trim(); + printer.Name = @object.GetValue(properties, "name")?.Trim(); + printer.Port = @object.GetValue(properties, "portname")?.Trim(); + printer.Location = @object.GetValue(properties, "location")?.Trim(); + printer.Comment = @object.GetValue(properties, "comment")?.Trim(); + + printers.Add(printer); + } + } + + return printers; + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/ProcessorHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/ProcessorHandler.cs index 47052cc..2d3c72b 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/ProcessorHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/ProcessorHandler.cs @@ -1,143 +1,143 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management; using System.Runtime.Versioning; -namespace Insight.Agent.Network.Handlers -{ - [SupportedOSPlatform("windows")] - public class ProcessorHandler : IAgentMessageHandler - { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is GetInventory) - { - var result = new ProcessorList(); - result.AddRange(GetProcessors()); +namespace Insight.Agent.Network.Handlers; - await sender.SendAsync(result, cancellationToken); - } +[SupportedOSPlatform("windows")] +public class ProcessorHandler : IMessageHandler +{ + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is InventoryRequest) + { + var result = new ProcessorList(); + result.AddRange(GetProcessors()); + + await sender.SendAsync(result, cancellationToken); + } + } + + private static List GetProcessors() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select deviceid, name, manufacturer, socketdesignation, version, processorid, l2cachesize, l3cachesize, currentclockspeed, maxclockspeed, numberofcores, numberoflogicalprocessors, virtualizationfirmwareenabled from win32_processor") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_processor"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); } - private static List GetProcessors() + var processors = new List(); + + using (collection) { - using var searcher = new ManagementObjectSearcher + uint index = 0; + + foreach (ManagementObject @object in collection.Cast()) { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select deviceid, name, manufacturer, socketdesignation, version, processorid, l2cachesize, l3cachesize, currentclockspeed, maxclockspeed, numberofcores, numberoflogicalprocessors, virtualizationfirmwareenabled from win32_processor") - }; + var processor = new Processor(); - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_processor"); + var properties = @object.GetPropertyHashes(); - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } + processor.Index = index; + processor.DeviceId = @object.GetValue(properties, "deviceid")?.Trim(); + processor.Name = @object.GetValue(properties, "name")?.Trim(); + processor.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); + processor.Socket = @object.GetValue(properties, "socketdesignation")?.Trim(); + processor.Version = @object.GetValue(properties, "version")?.Trim(); + processor.SerialNumber = @object.GetValue(properties, "processorid")?.Trim(); + processor.CurrentSpeed = @object.GetValue(properties, "currentclockspeed"); + processor.MaxSpeed = @object.GetValue(properties, "maxclockspeed"); + processor.Cores = @object.GetValue(properties, "numberofcores"); + processor.LogicalCores = @object.GetValue(properties, "numberoflogicalprocessors"); + processor.Virtualization = @object.GetValue(properties, "virtualizationfirmwareenabled"); - var processors = new List(); + searcher.Query = new ObjectQuery("select level, maxcachesize from win32_cachememory"); - using (collection) - { - uint index = 0; - - foreach (ManagementObject @object in collection.Cast()) + if (searcher.TryGet(out var collection2) is false) { - var processor = new Processor(); + searcher.Query = new ObjectQuery("select * from win32_cachememory"); - var properties = @object.GetPropertyHashes(); + if (searcher.TryGet(out collection2) is false) throw new InvalidOperationException("WMI Collection NULL"); + } - processor.Index = index; - processor.DeviceId = @object.GetValue(properties, "deviceid")?.Trim(); - processor.Name = @object.GetValue(properties, "name")?.Trim(); - processor.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); - processor.Socket = @object.GetValue(properties, "socketdesignation")?.Trim(); - processor.Version = @object.GetValue(properties, "version")?.Trim(); - processor.SerialNumber = @object.GetValue(properties, "processorid")?.Trim(); - processor.CurrentSpeed = @object.GetValue(properties, "currentclockspeed"); - processor.MaxSpeed = @object.GetValue(properties, "maxclockspeed"); - processor.Cores = @object.GetValue(properties, "numberofcores"); - processor.LogicalCores = @object.GetValue(properties, "numberoflogicalprocessors"); - processor.Virtualization = @object.GetValue(properties, "virtualizationfirmwareenabled"); - - searcher.Query = new ObjectQuery("select level, maxcachesize from win32_cachememory"); - - if (searcher.TryGet(out var collection2) is false) + using (collection2) + { + foreach (ManagementObject @object2 in collection2.Cast()) { - searcher.Query = new ObjectQuery("select * from win32_cachememory"); + var properties2 = @object2.GetPropertyHashes(); - if (searcher.TryGet(out collection2) is false) throw new InvalidOperationException("WMI Collection NULL"); - } + ProcessorCacheLevelEnum? cacheLevel = null; - using (collection2) - { - foreach (ManagementObject @object2 in collection2.Cast()) + cacheLevel = (ProcessorCacheLevelEnum?)@object2.GetValue(properties2, "level"); + + if (cacheLevel is null) continue; + + var installedSize = @object2.GetValue(properties2, "maxcachesize"); + + switch (cacheLevel) { - var properties2 = @object2.GetPropertyHashes(); - - ProcessorCacheLevelEnum? cacheLevel = null; - - cacheLevel = (ProcessorCacheLevelEnum?)@object2.GetValue(properties2, "level"); - - if (cacheLevel is null) continue; - - var installedSize = @object2.GetValue(properties2, "maxcachesize"); - - switch (cacheLevel) - { - case ProcessorCacheLevelEnum.L1: - { - processor.L1Size = installedSize; - break; - } - case ProcessorCacheLevelEnum.L2: - { - processor.L2Size = installedSize; - break; - } - case ProcessorCacheLevelEnum.L3: - { - processor.L3Size = installedSize; - break; - } - } + case ProcessorCacheLevelEnum.L1: + { + processor.L1Size = installedSize; + break; + } + case ProcessorCacheLevelEnum.L2: + { + processor.L2Size = installedSize; + break; + } + case ProcessorCacheLevelEnum.L3: + { + processor.L3Size = installedSize; + break; + } } } - - processors.Add(processor); - index++; } + + processors.Add(processor); + index++; } - - return processors; } - private enum ProcessorCacheLevelEnum - { - L1 = 3, - L2 = 4, - L3 = 5, - } - - //private async ValueTask GetProcessorMetricAsync(CancellationToken cancellationToken) - //{ - // var metric = new Processor.Metric(); - - // if (ProcessorTimeCounter is null) - // { - // ProcessorTimeCounter = new PerformanceCounter - // { - // CategoryName = "Processor", - // CounterName = "% Processor Time", - // InstanceName = "_Total" - // }; - - // metric.ProcessorUsagePercentage = ProcessorTimeCounter.NextValue(); - // await Task.Delay(1000, cancellationToken).ConfigureAwait(false); - // } - - // metric.Timestamp = DateTime.Now; - // metric.ProcessorUsagePercentage = ProcessorTimeCounter?.NextValue(); - // return metric; - //} + return processors; } + + private enum ProcessorCacheLevelEnum + { + L1 = 3, + L2 = 4, + L3 = 5, + } + + //private async ValueTask GetProcessorMetricAsync(CancellationToken cancellationToken) + //{ + // var metric = new Processor.Metric(); + + // if (ProcessorTimeCounter is null) + // { + // ProcessorTimeCounter = new PerformanceCounter + // { + // CategoryName = "Processor", + // CounterName = "% Processor Time", + // InstanceName = "_Total" + // }; + + // metric.ProcessorUsagePercentage = ProcessorTimeCounter.NextValue(); + // await Task.Delay(1000, cancellationToken).ConfigureAwait(false); + // } + + // metric.Timestamp = DateTime.Now; + // metric.ProcessorUsagePercentage = ProcessorTimeCounter?.NextValue(); + // return metric; + //} } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/ServiceHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/ServiceHandler.cs index db3fb34..e3ce58a 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/ServiceHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/ServiceHandler.cs @@ -1,118 +1,118 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management; using System.Runtime.Versioning; using System.ServiceProcess; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class ServiceHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class ServiceHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - var result = new ServiceList(); - result.AddRange(GetServices()); + var result = new ServiceList(); + result.AddRange(GetServices()); - await sender.SendAsync(result, cancellationToken); - } - } - - private static List GetServices() - { - var services = new List(); - - var serviceControllers = ServiceController.GetServices()?.OrderBy(s => s.DisplayName)?.ToList(); - if (serviceControllers is null || serviceControllers.Any() is false) throw new InvalidOperationException("SERVICE Collection NULL"); - - foreach (var sc in serviceControllers) - { - var status = sc.Status switch - { - ServiceControllerStatus.Stopped => Service.ServiceStatus.Stopped, - ServiceControllerStatus.StartPending => Service.ServiceStatus.StartPending, - ServiceControllerStatus.StopPending => Service.ServiceStatus.StopPending, - ServiceControllerStatus.Running => Service.ServiceStatus.Running, - ServiceControllerStatus.ContinuePending => Service.ServiceStatus.ContinuePending, - ServiceControllerStatus.PausePending => Service.ServiceStatus.PausePending, - ServiceControllerStatus.Paused => Service.ServiceStatus.Paused, - _ => Service.ServiceStatus.Unknown - }; - - var mode = sc.StartType switch - { - ServiceStartMode.Boot => Service.ServiceMode.Boot, - ServiceStartMode.System => Service.ServiceMode.System, - ServiceStartMode.Automatic => Service.ServiceMode.Automatic, - ServiceStartMode.Manual => Service.ServiceMode.Manual, - ServiceStartMode.Disabled => Service.ServiceMode.Disabled, - _ => Service.ServiceMode.Unknown, - }; - - var service = new Service - { - Name = sc.ServiceName?.Trim(), - Display = sc.DisplayName?.Trim(), - Status = status, - StartMode = mode - }; - - services.Add(service); - } - - // additional infos - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("SELECT processid, name, description, pathname, startname, delayedautostart from win32_service") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_service"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var services2 = new List(); - - using (collection) - { - foreach (ManagementObject @object in collection.Cast()) - { - var service2 = new Service(); - - var properties = @object.GetPropertyHashes(); - - service2.Name = @object.GetValue(properties, "name")?.Trim(); - service2.ProcessId = @object.GetValue(properties, "processid"); - service2.Description = @object.GetValue(properties, "description")?.Trim(); - service2.PathName = @object.GetValue(properties, "pathname")?.Trim(); - service2.Account = @object.GetValue(properties, "startname")?.Trim(); - service2.Delay = @object.GetValue(properties, "delayedautostart"); - - services2.Add(service2); - } - } - - if (services2.Any() is false) return services; - - foreach (var svc in services) - { - var map = services2.Where(p => p.Name == svc.Name).FirstOrDefault(); - - if (map is null) continue; - - svc.ProcessId = map.ProcessId; - svc.Description = map.Description; - svc.PathName = map.PathName; - svc.Account = map.Account; - svc.Delay = map.Delay; - } - - return services.OrderBy(x => x.Name).ToList(); + await sender.SendAsync(result, cancellationToken); } } + + private static List GetServices() + { + var services = new List(); + + var serviceControllers = ServiceController.GetServices()?.OrderBy(s => s.DisplayName)?.ToList(); + if (serviceControllers is null || serviceControllers.Any() is false) throw new InvalidOperationException("SERVICE Collection NULL"); + + foreach (var sc in serviceControllers) + { + var status = sc.Status switch + { + ServiceControllerStatus.Stopped => Service.ServiceStatus.Stopped, + ServiceControllerStatus.StartPending => Service.ServiceStatus.StartPending, + ServiceControllerStatus.StopPending => Service.ServiceStatus.StopPending, + ServiceControllerStatus.Running => Service.ServiceStatus.Running, + ServiceControllerStatus.ContinuePending => Service.ServiceStatus.ContinuePending, + ServiceControllerStatus.PausePending => Service.ServiceStatus.PausePending, + ServiceControllerStatus.Paused => Service.ServiceStatus.Paused, + _ => Service.ServiceStatus.Unknown + }; + + var mode = sc.StartType switch + { + ServiceStartMode.Boot => Service.ServiceMode.Boot, + ServiceStartMode.System => Service.ServiceMode.System, + ServiceStartMode.Automatic => Service.ServiceMode.Automatic, + ServiceStartMode.Manual => Service.ServiceMode.Manual, + ServiceStartMode.Disabled => Service.ServiceMode.Disabled, + _ => Service.ServiceMode.Unknown, + }; + + var service = new Service + { + Name = sc.ServiceName?.Trim(), + Display = sc.DisplayName?.Trim(), + Status = status, + StartMode = mode + }; + + services.Add(service); + } + + // additional infos + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("SELECT processid, name, description, pathname, startname, delayedautostart from win32_service") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_service"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var services2 = new List(); + + using (collection) + { + foreach (ManagementObject @object in collection.Cast()) + { + var service2 = new Service(); + + var properties = @object.GetPropertyHashes(); + + service2.Name = @object.GetValue(properties, "name")?.Trim(); + service2.ProcessId = @object.GetValue(properties, "processid"); + service2.Description = @object.GetValue(properties, "description")?.Trim(); + service2.PathName = @object.GetValue(properties, "pathname")?.Trim(); + service2.Account = @object.GetValue(properties, "startname")?.Trim(); + service2.Delay = @object.GetValue(properties, "delayedautostart"); + + services2.Add(service2); + } + } + + if (services2.Any() is false) return services; + + foreach (var svc in services) + { + var map = services2.Where(p => p.Name == svc.Name).FirstOrDefault(); + + if (map is null) continue; + + svc.ProcessId = map.ProcessId; + svc.Description = map.Description; + svc.PathName = map.PathName; + svc.Account = map.Account; + svc.Delay = map.Delay; + } + + return services.OrderBy(x => x.Name).ToList(); + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/SessionHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/SessionHandler.cs index c857127..3b331ca 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/SessionHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/SessionHandler.cs @@ -1,252 +1,252 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Runtime.InteropServices; using System.Runtime.Versioning; -namespace Insight.Agent.Network.Handlers -{ - [SupportedOSPlatform("windows")] - public class SessionHandler : IAgentMessageHandler - { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is GetInventory) - { - var result = new SessionList(); - result.AddRange(GetSessions()); +namespace Insight.Agent.Network.Handlers; - await sender.SendAsync(result, cancellationToken); - } +[SupportedOSPlatform("windows")] +public class SessionHandler : IMessageHandler +{ + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is InventoryRequest) + { + var result = new SessionList(); + result.AddRange(GetSessions()); + + await sender.SendAsync(result, cancellationToken); + } + } + + private static List GetSessions() + { + var query = NativeMethods.GetSessions(); + + var sessions = new List(); + + foreach (var s in NativeMethods.GetSessions()) + { + sessions.Add(new Session + { + Sid = s.SessionId.ToString(), + User = s.Username, + Type = s.Workstation, + Status = s.State.ToString(), + Remote = s.IPAddress + }); } - private static List GetSessions() + return sessions; + } + + private static partial class NativeMethods + { + //public const int WTS_CURRENT_SESSION = -1; + + [DllImport("wtsapi32.dll")] + static extern int WTSEnumerateSessions( + nint pServer, + [MarshalAs(UnmanagedType.U4)] int iReserved, + [MarshalAs(UnmanagedType.U4)] int iVersion, + ref nint pSessionInfo, + [MarshalAs(UnmanagedType.U4)] ref int iCount); + + [DllImport("Wtsapi32.dll")] + private static extern bool WTSQuerySessionInformation( + nint pServer, + int iSessionID, + WTS_INFO_CLASS oInfoClass, + out nint pBuffer, + out uint iBytesReturned); + + [DllImport("wtsapi32.dll")] + static extern void WTSFreeMemory( + nint pMemory); + + [StructLayout(LayoutKind.Sequential)] + private struct WTS_CLIENT_ADDRESS { - var query = NativeMethods.GetSessions(); + public int iAddressFamily; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] + public byte[] bAddress; + } - var sessions = new List(); + [StructLayout(LayoutKind.Sequential)] + private struct WTS_SESSION_INFO + { + public int iSessionID; + [MarshalAs(UnmanagedType.LPStr)] + public string sWinsWorkstationName; + public WTS_CONNECTSTATE_CLASS oState; + } - foreach (var s in NativeMethods.GetSessions()) + [StructLayout(LayoutKind.Sequential)] + private struct WTS_CLIENT_DISPLAY + { + public int iHorizontalResolution; + public int iVerticalResolution; + //1 = The display uses 4 bits per pixel for a maximum of 16 colors. + //2 = The display uses 8 bits per pixel for a maximum of 256 colors. + //4 = The display uses 16 bits per pixel for a maximum of 2^16 colors. + //8 = The display uses 3-byte RGB values for a maximum of 2^24 colors. + //16 = The display uses 15 bits per pixel for a maximum of 2^15 colors. + public int iColorDepth; + } + + public enum WTS_CONNECTSTATE_CLASS + { + WTSActive, + WTSConnected, + WTSConnectQuery, + WTSShadow, + WTSDisconnected, + WTSIdle, + WTSListen, + WTSReset, + WTSDown, + WTSInit + } + + public enum WTS_INFO_CLASS + { + WTSInitialProgram, + WTSApplicationName, + WTSWorkingDirectory, + WTSOEMId, + WTSSessionId, + WTSUserName, + WTSWinStationName, + WTSDomainName, + WTSConnectState, + WTSClientBuildNumber, + WTSClientName, + WTSClientDirectory, + WTSClientProductId, + WTSClientHardwareId, + WTSClientAddress, + WTSClientDisplay, + WTSClientProtocolType, + WTSIdleTime, + WTSLogonTime, + WTSIncomingBytes, + WTSOutgoingBytes, + WTSIncomingFrames, + WTSOutgoingFrames, + WTSClientInfo, + WTSSessionInfo, + WTSConfigInfo, + WTSValidationInfo, + WTSSessionAddressV4, + WTSIsRemoteSession + } + + public class WTSSession + { + public int SessionId { get; set; } + public WTS_CONNECTSTATE_CLASS State { get; set; } + public string? Workstation { get; set; } + public string? IPAddress { get; set; } + public string? Username { get; set; } + public int HorizontalResolution { get; set; } + public int VerticalResolution { get; set; } + public int ColorDepth { get; set; } + public string? ClientApplicationDirectory { get; set; } + } + + public static IEnumerable GetSessions() + { + var sessions = new List(); + + var pServer = nint.Zero; + var pSessionInfo = nint.Zero; + + try { - sessions.Add(new Session + var count = 0; + var sessionCount = WTSEnumerateSessions(pServer, 0, 1, ref pSessionInfo, ref count); + var dataSize = (long)Marshal.SizeOf(typeof(WTS_SESSION_INFO)); + var current = (long)pSessionInfo; + + if (sessionCount <= 0) + return sessions; + + for (int i = 0; i < count; i++) { - Sid = s.SessionId.ToString(), - User = s.Username, - Type = s.Workstation, - Status = s.State.ToString(), - Remote = s.IPAddress - }); + if (Marshal.PtrToStructure((nint)current, typeof(WTS_SESSION_INFO)) is not object sessionStructure) + continue; + + var sessionInfo = (WTS_SESSION_INFO)sessionStructure; + current += dataSize; + + var session = new WTSSession + { + SessionId = sessionInfo.iSessionID, + State = sessionInfo.oState, + Workstation = sessionInfo.sWinsWorkstationName, + }; + + var returned = (uint)0; + + // get terminal user address + var address = nint.Zero; + var clientAddress = new WTS_CLIENT_ADDRESS(); + + if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientAddress, out address, out returned) == true) + { + if (Marshal.PtrToStructure(address, clientAddress.GetType()) is not object addressStructure) + break; + + clientAddress = (WTS_CLIENT_ADDRESS)addressStructure; + session.IPAddress = clientAddress.bAddress[2] + "." + clientAddress.bAddress[3] + "." + clientAddress.bAddress[4] + "." + clientAddress.bAddress[5]; + } + + // get terminal user name + if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSUserName, out address, out returned) == true) + { + session.Username = Marshal.PtrToStringAnsi(address); + } + + // get terminal user domain name + if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSDomainName, out address, out returned) == true) + { + session.Username = Marshal.PtrToStringAnsi(address) + @"\" + session.Username; + } + + // get terminal user display informations + var clientDisplay = new WTS_CLIENT_DISPLAY(); + + if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientDisplay, out address, out returned) == true) + { + if (Marshal.PtrToStructure(address, clientDisplay.GetType()) is not object displayStructure) + break; + + clientDisplay = (WTS_CLIENT_DISPLAY)displayStructure; + session.HorizontalResolution = clientDisplay.iHorizontalResolution; + session.VerticalResolution = clientDisplay.iVerticalResolution; + session.ColorDepth = clientDisplay.iColorDepth; + } + + // get terminal user application directory + if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientDirectory, out address, out returned) == true) + { + session.ClientApplicationDirectory = Marshal.PtrToStringAnsi(address); + } + + sessions.Add(session); + } + } + catch (Exception) + { + throw; + } + finally + { + WTSFreeMemory(pSessionInfo); } return sessions; } - - private static partial class NativeMethods - { - //public const int WTS_CURRENT_SESSION = -1; - - [DllImport("wtsapi32.dll")] - static extern int WTSEnumerateSessions( - nint pServer, - [MarshalAs(UnmanagedType.U4)] int iReserved, - [MarshalAs(UnmanagedType.U4)] int iVersion, - ref nint pSessionInfo, - [MarshalAs(UnmanagedType.U4)] ref int iCount); - - [DllImport("Wtsapi32.dll")] - private static extern bool WTSQuerySessionInformation( - nint pServer, - int iSessionID, - WTS_INFO_CLASS oInfoClass, - out nint pBuffer, - out uint iBytesReturned); - - [DllImport("wtsapi32.dll")] - static extern void WTSFreeMemory( - nint pMemory); - - [StructLayout(LayoutKind.Sequential)] - private struct WTS_CLIENT_ADDRESS - { - public int iAddressFamily; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] - public byte[] bAddress; - } - - [StructLayout(LayoutKind.Sequential)] - private struct WTS_SESSION_INFO - { - public int iSessionID; - [MarshalAs(UnmanagedType.LPStr)] - public string sWinsWorkstationName; - public WTS_CONNECTSTATE_CLASS oState; - } - - [StructLayout(LayoutKind.Sequential)] - private struct WTS_CLIENT_DISPLAY - { - public int iHorizontalResolution; - public int iVerticalResolution; - //1 = The display uses 4 bits per pixel for a maximum of 16 colors. - //2 = The display uses 8 bits per pixel for a maximum of 256 colors. - //4 = The display uses 16 bits per pixel for a maximum of 2^16 colors. - //8 = The display uses 3-byte RGB values for a maximum of 2^24 colors. - //16 = The display uses 15 bits per pixel for a maximum of 2^15 colors. - public int iColorDepth; - } - - public enum WTS_CONNECTSTATE_CLASS - { - WTSActive, - WTSConnected, - WTSConnectQuery, - WTSShadow, - WTSDisconnected, - WTSIdle, - WTSListen, - WTSReset, - WTSDown, - WTSInit - } - - public enum WTS_INFO_CLASS - { - WTSInitialProgram, - WTSApplicationName, - WTSWorkingDirectory, - WTSOEMId, - WTSSessionId, - WTSUserName, - WTSWinStationName, - WTSDomainName, - WTSConnectState, - WTSClientBuildNumber, - WTSClientName, - WTSClientDirectory, - WTSClientProductId, - WTSClientHardwareId, - WTSClientAddress, - WTSClientDisplay, - WTSClientProtocolType, - WTSIdleTime, - WTSLogonTime, - WTSIncomingBytes, - WTSOutgoingBytes, - WTSIncomingFrames, - WTSOutgoingFrames, - WTSClientInfo, - WTSSessionInfo, - WTSConfigInfo, - WTSValidationInfo, - WTSSessionAddressV4, - WTSIsRemoteSession - } - - public class WTSSession - { - public int SessionId { get; set; } - public WTS_CONNECTSTATE_CLASS State { get; set; } - public string? Workstation { get; set; } - public string? IPAddress { get; set; } - public string? Username { get; set; } - public int HorizontalResolution { get; set; } - public int VerticalResolution { get; set; } - public int ColorDepth { get; set; } - public string? ClientApplicationDirectory { get; set; } - } - - public static IEnumerable GetSessions() - { - var sessions = new List(); - - var pServer = nint.Zero; - var pSessionInfo = nint.Zero; - - try - { - var count = 0; - var sessionCount = WTSEnumerateSessions(pServer, 0, 1, ref pSessionInfo, ref count); - var dataSize = (long)Marshal.SizeOf(typeof(WTS_SESSION_INFO)); - var current = (long)pSessionInfo; - - if (sessionCount <= 0) - return sessions; - - for (int i = 0; i < count; i++) - { - if (Marshal.PtrToStructure((nint)current, typeof(WTS_SESSION_INFO)) is not object sessionStructure) - continue; - - var sessionInfo = (WTS_SESSION_INFO)sessionStructure; - current += dataSize; - - var session = new WTSSession - { - SessionId = sessionInfo.iSessionID, - State = sessionInfo.oState, - Workstation = sessionInfo.sWinsWorkstationName, - }; - - var returned = (uint)0; - - // get terminal user address - var address = nint.Zero; - var clientAddress = new WTS_CLIENT_ADDRESS(); - - if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientAddress, out address, out returned) == true) - { - if (Marshal.PtrToStructure(address, clientAddress.GetType()) is not object addressStructure) - break; - - clientAddress = (WTS_CLIENT_ADDRESS)addressStructure; - session.IPAddress = clientAddress.bAddress[2] + "." + clientAddress.bAddress[3] + "." + clientAddress.bAddress[4] + "." + clientAddress.bAddress[5]; - } - - // get terminal user name - if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSUserName, out address, out returned) == true) - { - session.Username = Marshal.PtrToStringAnsi(address); - } - - // get terminal user domain name - if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSDomainName, out address, out returned) == true) - { - session.Username = Marshal.PtrToStringAnsi(address) + @"\" + session.Username; - } - - // get terminal user display informations - var clientDisplay = new WTS_CLIENT_DISPLAY(); - - if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientDisplay, out address, out returned) == true) - { - if (Marshal.PtrToStructure(address, clientDisplay.GetType()) is not object displayStructure) - break; - - clientDisplay = (WTS_CLIENT_DISPLAY)displayStructure; - session.HorizontalResolution = clientDisplay.iHorizontalResolution; - session.VerticalResolution = clientDisplay.iVerticalResolution; - session.ColorDepth = clientDisplay.iColorDepth; - } - - // get terminal user application directory - if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientDirectory, out address, out returned) == true) - { - session.ClientApplicationDirectory = Marshal.PtrToStringAnsi(address); - } - - sessions.Add(session); - } - } - catch (Exception) - { - throw; - } - finally - { - WTSFreeMemory(pSessionInfo); - } - - return sessions; - } - } } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/SoftwareHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/SoftwareHandler.cs index 806c2d4..c11fd3a 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/SoftwareHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/SoftwareHandler.cs @@ -1,119 +1,119 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Microsoft.Win32; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.AccessControl; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +internal class SoftwareHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - internal class SoftwareHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - var x64 = Task.Run(() => ApplicationRegistryQuery(RegistryView.Registry64), cancellationToken); - var x86 = Task.Run(() => ApplicationRegistryQuery(RegistryView.Registry32), cancellationToken); + var x64 = Task.Run(() => ApplicationRegistryQuery(RegistryView.Registry64), 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(); - result.AddRange(x64.Result); - result.AddRange(x86.Result.Where(p => result.All(app => p.Name != app.Name && p.Version != app.Version))); + var result = new ApplicationList(); + result.AddRange(x64.Result); + result.AddRange(x86.Result.Where(p => result.All(app => p.Name != app.Name && p.Version != app.Version))); - await sender.SendAsync(result, cancellationToken); - } - } - - private static IEnumerable ApplicationRegistryQuery(RegistryView registryView) - { - using var registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView); - - using var key = registry.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\", RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey); - if (key is null) throw new NullReferenceException(nameof(key)); - - var apps = new List(); - - var architecture = registryView switch - { - RegistryView.Registry32 => Architecture.X86, - _ => Architecture.X64 - }; - - foreach (string name in key.GetSubKeyNames()) - { - using var query = key.OpenSubKey(name); - if (query is null) continue; - - var app = new Application - { - Architecture = architecture - }; - - if (query.GetValue("DisplayName")?.ToString()?.Trim() is string displayName && string.IsNullOrWhiteSpace(displayName) is false) - { - app.Name = displayName; - } - - if (query.GetValue("Publisher")?.ToString()?.Trim() is string publisher && string.IsNullOrWhiteSpace(publisher) is false) - { - app.Publisher = publisher; - } - - if (query.GetValue("DisplayVersion")?.ToString()?.Trim() is string version && string.IsNullOrWhiteSpace(version) is false) - { - app.Version = version; - } - - if (query.GetValue("InstallLocation")?.ToString()?.Trim() is string location && string.IsNullOrWhiteSpace(location) is false) - { - app.Location = location; - } - - if (query.GetValue("InstallSource")?.ToString()?.Trim() is string source && string.IsNullOrWhiteSpace(source) is false) - { - app.Source = source; - } - - if (query.GetValue("UninstallString")?.ToString()?.Trim() is string uninstall && string.IsNullOrWhiteSpace(uninstall) is false) - { - app.Uninstall = uninstall; - } - - if (app.Uninstall is null) - { - if (query.GetValue("UninstallString_Hidden")?.ToString()?.Trim() is string uninstall2 && string.IsNullOrWhiteSpace(uninstall2) is false) - { - app.Uninstall = uninstall2; - } - } - - if (query.GetValue("InstallDate")?.ToString()?.Trim() is string installDate) - { - if (DateTime.TryParseExact(installDate, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime valid)) - { - app.InstallDate = valid; - } - - if (app.InstallDate is null) - { - if (DateTime.TryParseExact(installDate, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime valid2)) - { - app.InstallDate = valid2; - } - } - } - - if (app.Name is not null) - { - apps.Add(app); - } - } - - return apps; + await sender.SendAsync(result, cancellationToken); } } + + private static IEnumerable ApplicationRegistryQuery(RegistryView registryView) + { + using var registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView); + + using var key = registry.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\", RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey); + if (key is null) throw new NullReferenceException(nameof(key)); + + var apps = new List(); + + var architecture = registryView switch + { + RegistryView.Registry32 => Architecture.X86, + _ => Architecture.X64 + }; + + foreach (string name in key.GetSubKeyNames()) + { + using var query = key.OpenSubKey(name); + if (query is null) continue; + + var app = new Application + { + Architecture = architecture + }; + + if (query.GetValue("DisplayName")?.ToString()?.Trim() is string displayName && string.IsNullOrWhiteSpace(displayName) is false) + { + app.Name = displayName; + } + + if (query.GetValue("Publisher")?.ToString()?.Trim() is string publisher && string.IsNullOrWhiteSpace(publisher) is false) + { + app.Publisher = publisher; + } + + if (query.GetValue("DisplayVersion")?.ToString()?.Trim() is string version && string.IsNullOrWhiteSpace(version) is false) + { + app.Version = version; + } + + if (query.GetValue("InstallLocation")?.ToString()?.Trim() is string location && string.IsNullOrWhiteSpace(location) is false) + { + app.Location = location; + } + + if (query.GetValue("InstallSource")?.ToString()?.Trim() is string source && string.IsNullOrWhiteSpace(source) is false) + { + app.Source = source; + } + + if (query.GetValue("UninstallString")?.ToString()?.Trim() is string uninstall && string.IsNullOrWhiteSpace(uninstall) is false) + { + app.Uninstall = uninstall; + } + + if (app.Uninstall is null) + { + if (query.GetValue("UninstallString_Hidden")?.ToString()?.Trim() is string uninstall2 && string.IsNullOrWhiteSpace(uninstall2) is false) + { + app.Uninstall = uninstall2; + } + } + + if (query.GetValue("InstallDate")?.ToString()?.Trim() is string installDate) + { + if (DateTime.TryParseExact(installDate, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime valid)) + { + app.InstallDate = valid; + } + + if (app.InstallDate is null) + { + if (DateTime.TryParseExact(installDate, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime valid2)) + { + app.InstallDate = valid2; + } + } + } + + if (app.Name is not null) + { + apps.Add(app); + } + } + + return apps; + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/StoragePoolHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/StoragePoolHandler.cs index 84b5506..76466c7 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/StoragePoolHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/StoragePoolHandler.cs @@ -1,308 +1,308 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management; using System.Runtime.Versioning; -using static Insight.Agent.Messages.PhysicalDisk; -using static Insight.Agent.Messages.StoragePool; -using static Insight.Agent.Messages.VirtualDisk; +using static Insight.Domain.Messages.Agent.PhysicalDisk; +using static Insight.Domain.Messages.Agent.StoragePool; +using static Insight.Domain.Messages.Agent.VirtualDisk; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class StoragePoolHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class StoragePoolHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - var result = new StoragePoolList(); - result.AddRange(GetStoragePool()); + var result = new StoragePoolList(); + result.AddRange(GetStoragePool()); - await sender.SendAsync(result, cancellationToken); - } - } - - private static List GetStoragePool() - { - if (Environment.OSVersion.Version.Major < 6 || Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor < 2) - { - throw new PlatformNotSupportedException(); - } - - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\microsoft\windows\storage"), - Query = new ObjectQuery("select objectid, uniqueid, name, friendlyname, resiliencysettingnamedefault, isprimordial, isreadonly, isclustered, size, allocatedsize, logicalsectorsize, operationalstatus, healthstatus from msft_storagepool") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from msft_storagepool"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var pools = new List(); - - using (collection) - { - foreach (ManagementObject @object in collection.Cast()) - { - var pool = new StoragePool(); - - var properties = @object.GetPropertyHashes(); - - pool.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim(); - pool.Name = @object.GetValue(properties, "name")?.Trim(); - pool.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim(); - - if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null) - { - pool.States = operationals.Select(p => (StoragePool.OperationalState)p).ToList(); - } - - pool.Health = (StoragePool.HealthState)@object.GetValue(properties, "healthstatus"); - pool.RetireMissingPhysicalDisks = (RetireMissingPhysicalDisksEnum)@object.GetValue(properties, "retiremissingphysicaldisks"); - pool.Resiliency = @object.GetValue(properties, "resiliencysettingnamedefault")?.Trim(); - pool.IsPrimordial = @object.GetValue(properties, "isprimordial"); - pool.IsReadOnly = @object.GetValue(properties, "isreadonly"); - pool.IsClustered = @object.GetValue(properties, "isclustered"); - pool.Size = @object.GetValue(properties, "size"); - pool.AllocatedSize = @object.GetValue(properties, "allocatedsize"); - pool.SectorSize = @object.GetValue(properties, "logicalsectorsize"); - - if (@object.GetValue(properties, "objectid") is string objectId) - { - pool.PhysicalDisks = QueryPhysicalDisksByStoragePool(objectId); - pool.VirtualDisks = QueryVirtualDisksByStoragePool(objectId); - } - - pools.Add(pool); - } - } - - return pools; - } - - private static List 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(); - - using (collection) - { - foreach (ManagementObject @object in collection.Cast()) - { - var disk = new PhysicalDisk(); - - var properties = @object.GetPropertyHashes(); - - disk.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim(); - disk.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim(); - disk.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); - disk.Model = @object.GetValue(properties, "model")?.Trim(); - disk.MediaType = @object.GetValue(properties, "mediatype"); - disk.BusType = @object.GetValue(properties, "bustype"); - - if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null) - { - disk.States = operationals.Select(p => (PhysicalDisk.OperationalState)p).ToList(); - } - - disk.Health = (PhysicalDisk.HealthState)@object.GetValue(properties, "healthstatus"); - - if (@object.TryGetValue(properties, "supportedusages", out var supportedusages) && supportedusages is not null) - { - disk.SupportedUsages = supportedusages.Select(p => (SupportedUsagesEnum)p).ToList(); - } - - disk.Usage = @object.GetValue(properties, "usage"); - disk.PhysicalLocation = @object.GetValue(properties, "physicallocation")?.Trim(); - disk.SerialNumber = @object.GetValue(properties, "serialnumber")?.Trim(); - disk.FirmwareVersion = @object.GetValue(properties, "firmwareversion")?.Trim(); - disk.Size = @object.GetValue(properties, "size"); - disk.AllocatedSize = @object.GetValue(properties, "allocatedsize"); - disk.LogicalSectorSize = @object.GetValue(properties, "logicalsectorsize"); - disk.PhysicalSectorSize = @object.GetValue(properties, "physicalsectorsize"); - disk.VirtualDiskFootprint = @object.GetValue(properties, "virtualdiskfootprint"); - - disks.Add(disk); - } - } - - return disks; - } - - private static List 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(); - - using (collection) - { - foreach (ManagementObject @object in collection.Cast()) - { - var disk = new VirtualDisk(); - - var properties = @object.GetPropertyHashes(); - - disk.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim(); - disk.Name = @object.GetValue(properties, "name")?.Trim(); - disk.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim(); - disk.AccessType = (AccessTypeEnum)@object.GetValue(properties, "access"); - disk.ProvisioningType = (ProvisioningTypeEnum)@object.GetValue(properties, "provisioningtype"); - disk.PhysicalDiskRedundancy = @object.GetValue(properties, "physicaldiskredundancy"); - disk.ResiliencySettingName = @object.GetValue(properties, "resiliencysettingname")?.Trim(); - disk.Deduplication = @object.GetValue(properties, "isdeduplicationenabled"); - disk.IsSnapshot = @object.GetValue(properties, "issnapshot"); - - if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null) - { - disk.States = operationals.Select(p => (VirtualDisk.OperationalState)p).ToList(); - } - - disk.Health = (VirtualDisk.HealthState)@object.GetValue(properties, "healthstatus"); - disk.Size = @object.GetValue(properties, "size"); - disk.AllocatedSize = @object.GetValue(properties, "allocatedsize"); - disk.FootprintOnPool = @object.GetValue(properties, "footprintonpool"); - disk.ReadCacheSize = @object.GetValue(properties, "readcachesize"); - disk.WriteCacheSize = @object.GetValue(properties, "writecachesize"); - - disks.Add(disk); - } - } - - return disks; - } - - private static List QueryPhysicalDisksByStoragePool(string storagePoolObjectId) - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\microsoft\windows\storage"), - Query = new ObjectQuery("ASSOCIATORS OF {MSFT_StoragePool.ObjectId=\"" + Helpers.EscapeWql(storagePoolObjectId) + "\"} WHERE AssocClass = MSFT_StoragePoolToPhysicalDisk") - }; - - if (searcher.TryGet(out var collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - - var disks = new List(); - - using (collection) - { - foreach (ManagementObject @object in collection) - { - var disk = new PhysicalDisk(); - - var properties = @object.GetPropertyHashes(); - - disk.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim(); - disk.DeviceId = @object.GetValue(properties, "deviceid")?.Trim(); - disk.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim(); - disk.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); - disk.Model = @object.GetValue(properties, "model")?.Trim(); - disk.MediaType = @object.GetValue(properties, "mediatype"); - disk.BusType = @object.GetValue(properties, "bustype"); - - if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null) - { - disk.States = operationals.Select(p => (PhysicalDisk.OperationalState)p).ToList(); - } - - disk.Health = (PhysicalDisk.HealthState)@object.GetValue(properties, "healthstatus"); - - if (@object.TryGetValue(properties, "supportedusages", out var supportedusages) && supportedusages is not null) - { - disk.SupportedUsages = supportedusages.Select(p => (SupportedUsagesEnum)p).ToList(); - } - - disk.Usage = @object.GetValue(properties, "usage"); - disk.PhysicalLocation = @object.GetValue(properties, "physicallocation")?.Trim(); - disk.SerialNumber = @object.GetValue(properties, "serialnumber")?.Trim(); - disk.FirmwareVersion = @object.GetValue(properties, "firmwareversion")?.Trim(); - disk.Size = @object.GetValue(properties, "size"); - disk.AllocatedSize = @object.GetValue(properties, "allocatedsize"); - disk.LogicalSectorSize = @object.GetValue(properties, "logicalsectorsize"); - disk.PhysicalSectorSize = @object.GetValue(properties, "physicalsectorsize"); - disk.VirtualDiskFootprint = @object.GetValue(properties, "virtualdiskfootprint"); - - disks.Add(disk); - } - } - - return disks; - } - - private static List QueryVirtualDisksByStoragePool(string storagePoolObjectId) - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\microsoft\windows\storage"), - Query = new ObjectQuery("ASSOCIATORS OF {MSFT_StoragePool.ObjectId=\"" + Helpers.EscapeWql(storagePoolObjectId) + "\"} WHERE AssocClass = MSFT_StoragePoolToVirtualDisk") - }; - - if (searcher.TryGet(out var collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - - var disks = new List(); - - using (collection) - { - foreach (ManagementObject @object in collection) - { - var disk = new VirtualDisk(); - - var properties = @object.GetPropertyHashes(); - - disk.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim(); - disk.Name = @object.GetValue(properties, "name")?.Trim(); - disk.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim(); - disk.AccessType = (AccessTypeEnum)@object.GetValue(properties, "access"); - disk.ProvisioningType = (ProvisioningTypeEnum)@object.GetValue(properties, "provisioningtype"); - disk.PhysicalDiskRedundancy = @object.GetValue(properties, "physicaldiskredundancy"); - disk.ResiliencySettingName = @object.GetValue(properties, "resiliencysettingname")?.Trim(); - disk.Deduplication = @object.GetValue(properties, "isdeduplicationenabled"); - disk.IsSnapshot = @object.GetValue(properties, "issnapshot"); - - if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null) - { - disk.States = operationals.Select(p => (VirtualDisk.OperationalState)p).ToList(); - } - - disk.Health = (VirtualDisk.HealthState)@object.GetValue(properties, "healthstatus"); - disk.Size = @object.GetValue(properties, "size"); - disk.AllocatedSize = @object.GetValue(properties, "allocatedsize"); - disk.FootprintOnPool = @object.GetValue(properties, "footprintonpool"); - disk.ReadCacheSize = @object.GetValue(properties, "readcachesize"); - disk.WriteCacheSize = @object.GetValue(properties, "writecachesize"); - - disks.Add(disk); - } - } - - return disks; + await sender.SendAsync(result, cancellationToken); } } + + private static List GetStoragePool() + { + if (Environment.OSVersion.Version.Major < 6 || Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor < 2) + { + throw new PlatformNotSupportedException(); + } + + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\microsoft\windows\storage"), + Query = new ObjectQuery("select objectid, uniqueid, name, friendlyname, resiliencysettingnamedefault, isprimordial, isreadonly, isclustered, size, allocatedsize, logicalsectorsize, operationalstatus, healthstatus from msft_storagepool") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from msft_storagepool"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var pools = new List(); + + using (collection) + { + foreach (ManagementObject @object in collection.Cast()) + { + var pool = new StoragePool(); + + var properties = @object.GetPropertyHashes(); + + pool.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim(); + pool.Name = @object.GetValue(properties, "name")?.Trim(); + pool.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim(); + + if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null) + { + pool.States = operationals.Select(p => (StoragePool.OperationalState)p).ToList(); + } + + pool.Health = (StoragePool.HealthState)@object.GetValue(properties, "healthstatus"); + pool.RetireMissingPhysicalDisks = (RetireMissingPhysicalDisksEnum)@object.GetValue(properties, "retiremissingphysicaldisks"); + pool.Resiliency = @object.GetValue(properties, "resiliencysettingnamedefault")?.Trim(); + pool.IsPrimordial = @object.GetValue(properties, "isprimordial"); + pool.IsReadOnly = @object.GetValue(properties, "isreadonly"); + pool.IsClustered = @object.GetValue(properties, "isclustered"); + pool.Size = @object.GetValue(properties, "size"); + pool.AllocatedSize = @object.GetValue(properties, "allocatedsize"); + pool.SectorSize = @object.GetValue(properties, "logicalsectorsize"); + + if (@object.GetValue(properties, "objectid") is string objectId) + { + pool.PhysicalDisks = QueryPhysicalDisksByStoragePool(objectId); + pool.VirtualDisks = QueryVirtualDisksByStoragePool(objectId); + } + + pools.Add(pool); + } + } + + return pools; + } + + private static List 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(); + + using (collection) + { + foreach (ManagementObject @object in collection.Cast()) + { + var disk = new PhysicalDisk(); + + var properties = @object.GetPropertyHashes(); + + disk.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim(); + disk.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim(); + disk.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); + disk.Model = @object.GetValue(properties, "model")?.Trim(); + disk.MediaType = @object.GetValue(properties, "mediatype"); + disk.BusType = @object.GetValue(properties, "bustype"); + + if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null) + { + disk.States = operationals.Select(p => (PhysicalDisk.OperationalState)p).ToList(); + } + + disk.Health = (PhysicalDisk.HealthState)@object.GetValue(properties, "healthstatus"); + + if (@object.TryGetValue(properties, "supportedusages", out var supportedusages) && supportedusages is not null) + { + disk.SupportedUsages = supportedusages.Select(p => (SupportedUsagesEnum)p).ToList(); + } + + disk.Usage = @object.GetValue(properties, "usage"); + disk.PhysicalLocation = @object.GetValue(properties, "physicallocation")?.Trim(); + disk.SerialNumber = @object.GetValue(properties, "serialnumber")?.Trim(); + disk.FirmwareVersion = @object.GetValue(properties, "firmwareversion")?.Trim(); + disk.Size = @object.GetValue(properties, "size"); + disk.AllocatedSize = @object.GetValue(properties, "allocatedsize"); + disk.LogicalSectorSize = @object.GetValue(properties, "logicalsectorsize"); + disk.PhysicalSectorSize = @object.GetValue(properties, "physicalsectorsize"); + disk.VirtualDiskFootprint = @object.GetValue(properties, "virtualdiskfootprint"); + + disks.Add(disk); + } + } + + return disks; + } + + private static List 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(); + + using (collection) + { + foreach (ManagementObject @object in collection.Cast()) + { + var disk = new VirtualDisk(); + + var properties = @object.GetPropertyHashes(); + + disk.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim(); + disk.Name = @object.GetValue(properties, "name")?.Trim(); + disk.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim(); + disk.AccessType = (AccessTypeEnum)@object.GetValue(properties, "access"); + disk.ProvisioningType = (ProvisioningTypeEnum)@object.GetValue(properties, "provisioningtype"); + disk.PhysicalDiskRedundancy = @object.GetValue(properties, "physicaldiskredundancy"); + disk.ResiliencySettingName = @object.GetValue(properties, "resiliencysettingname")?.Trim(); + disk.Deduplication = @object.GetValue(properties, "isdeduplicationenabled"); + disk.IsSnapshot = @object.GetValue(properties, "issnapshot"); + + if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null) + { + disk.States = operationals.Select(p => (VirtualDisk.OperationalState)p).ToList(); + } + + disk.Health = (VirtualDisk.HealthState)@object.GetValue(properties, "healthstatus"); + disk.Size = @object.GetValue(properties, "size"); + disk.AllocatedSize = @object.GetValue(properties, "allocatedsize"); + disk.FootprintOnPool = @object.GetValue(properties, "footprintonpool"); + disk.ReadCacheSize = @object.GetValue(properties, "readcachesize"); + disk.WriteCacheSize = @object.GetValue(properties, "writecachesize"); + + disks.Add(disk); + } + } + + return disks; + } + + private static List QueryPhysicalDisksByStoragePool(string storagePoolObjectId) + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\microsoft\windows\storage"), + Query = new ObjectQuery("ASSOCIATORS OF {MSFT_StoragePool.ObjectId=\"" + Helpers.EscapeWql(storagePoolObjectId) + "\"} WHERE AssocClass = MSFT_StoragePoolToPhysicalDisk") + }; + + if (searcher.TryGet(out var collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + + var disks = new List(); + + using (collection) + { + foreach (ManagementObject @object in collection) + { + var disk = new PhysicalDisk(); + + var properties = @object.GetPropertyHashes(); + + disk.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim(); + disk.DeviceId = @object.GetValue(properties, "deviceid")?.Trim(); + disk.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim(); + disk.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim(); + disk.Model = @object.GetValue(properties, "model")?.Trim(); + disk.MediaType = @object.GetValue(properties, "mediatype"); + disk.BusType = @object.GetValue(properties, "bustype"); + + if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null) + { + disk.States = operationals.Select(p => (PhysicalDisk.OperationalState)p).ToList(); + } + + disk.Health = (PhysicalDisk.HealthState)@object.GetValue(properties, "healthstatus"); + + if (@object.TryGetValue(properties, "supportedusages", out var supportedusages) && supportedusages is not null) + { + disk.SupportedUsages = supportedusages.Select(p => (SupportedUsagesEnum)p).ToList(); + } + + disk.Usage = @object.GetValue(properties, "usage"); + disk.PhysicalLocation = @object.GetValue(properties, "physicallocation")?.Trim(); + disk.SerialNumber = @object.GetValue(properties, "serialnumber")?.Trim(); + disk.FirmwareVersion = @object.GetValue(properties, "firmwareversion")?.Trim(); + disk.Size = @object.GetValue(properties, "size"); + disk.AllocatedSize = @object.GetValue(properties, "allocatedsize"); + disk.LogicalSectorSize = @object.GetValue(properties, "logicalsectorsize"); + disk.PhysicalSectorSize = @object.GetValue(properties, "physicalsectorsize"); + disk.VirtualDiskFootprint = @object.GetValue(properties, "virtualdiskfootprint"); + + disks.Add(disk); + } + } + + return disks; + } + + private static List QueryVirtualDisksByStoragePool(string storagePoolObjectId) + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\microsoft\windows\storage"), + Query = new ObjectQuery("ASSOCIATORS OF {MSFT_StoragePool.ObjectId=\"" + Helpers.EscapeWql(storagePoolObjectId) + "\"} WHERE AssocClass = MSFT_StoragePoolToVirtualDisk") + }; + + if (searcher.TryGet(out var collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + + var disks = new List(); + + using (collection) + { + foreach (ManagementObject @object in collection) + { + var disk = new VirtualDisk(); + + var properties = @object.GetPropertyHashes(); + + disk.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim(); + disk.Name = @object.GetValue(properties, "name")?.Trim(); + disk.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim(); + disk.AccessType = (AccessTypeEnum)@object.GetValue(properties, "access"); + disk.ProvisioningType = (ProvisioningTypeEnum)@object.GetValue(properties, "provisioningtype"); + disk.PhysicalDiskRedundancy = @object.GetValue(properties, "physicaldiskredundancy"); + disk.ResiliencySettingName = @object.GetValue(properties, "resiliencysettingname")?.Trim(); + disk.Deduplication = @object.GetValue(properties, "isdeduplicationenabled"); + disk.IsSnapshot = @object.GetValue(properties, "issnapshot"); + + if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null) + { + disk.States = operationals.Select(p => (VirtualDisk.OperationalState)p).ToList(); + } + + disk.Health = (VirtualDisk.HealthState)@object.GetValue(properties, "healthstatus"); + disk.Size = @object.GetValue(properties, "size"); + disk.AllocatedSize = @object.GetValue(properties, "allocatedsize"); + disk.FootprintOnPool = @object.GetValue(properties, "footprintonpool"); + disk.ReadCacheSize = @object.GetValue(properties, "readcachesize"); + disk.WriteCacheSize = @object.GetValue(properties, "writecachesize"); + + disks.Add(disk); + } + } + + return disks; + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/SystemInfoHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/SystemInfoHandler.cs index 6f9ee19..132b41f 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/SystemInfoHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/SystemInfoHandler.cs @@ -1,175 +1,175 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Microsoft.Win32; using System.Collections; using System.Management; using System.Runtime.Versioning; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class SystemInfoHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class SystemInfoHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - await sender.SendAsync(GetSystem(), cancellationToken); - } - } - - private static SystemInfo GetSystem() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select lastbootuptime, localdatetime, numberofprocesses from win32_operatingsystem") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_operatingsystem"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var system = new SystemInfo(); - - using (collection) - { - foreach (ManagementObject @object in collection.Cast()) - { - var properties = @object.GetPropertyHashes(); - - if (@object.TryGetValue(properties, "lastbootuptime", out var lastbootuptime)) - { - system.LastBootUpTime = ManagementDateTimeConverter.ToDateTime(lastbootuptime?.ToString()); - } - - if (@object.TryGetValue(properties, "localdatetime", out var localdatetime)) - { - system.LocalDateTime = ManagementDateTimeConverter.ToDateTime(localdatetime?.ToString()); - } - - system.Processes = @object.GetValue(properties, "numberofprocesses"); - - break; - } - } - - system.License = GetWindowsProductKeyFromRegistry(); - - return system; - } - - private static string GetWindowsProductKeyFromRegistry() - { - var localKey = - RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Environment.Is64BitOperatingSystem - ? RegistryView.Registry64 - : RegistryView.Registry32); - - var registryKeyValue = localKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")?.GetValue("DigitalProductId"); - if (registryKeyValue == null) - return "Failed to get DigitalProductId from registry"; - var digitalProductId = (byte[])registryKeyValue; - localKey.Close(); - var isWin8OrUp = - Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2 - || - Environment.OSVersion.Version.Major > 6; - return GetWindowsProductKeyFromDigitalProductId(digitalProductId, - isWin8OrUp ? DigitalProductIdVersion.Windows8AndUp : DigitalProductIdVersion.UpToWindows7); - } - - private static string GetWindowsProductKeyFromDigitalProductId(byte[] digitalProductId, DigitalProductIdVersion digitalProductIdVersion) - { - - var productKey = digitalProductIdVersion == DigitalProductIdVersion.Windows8AndUp - ? DecodeProductKeyWin8AndUp(digitalProductId) - : DecodeProductKey(digitalProductId); - return productKey; - } - - private static string DecodeProductKey(byte[] digitalProductId) - { - const int keyStartIndex = 52; - const int keyEndIndex = keyStartIndex + 15; - var digits = new[] - { - 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', - 'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9', - }; - const int decodeLength = 29; - const int decodeStringLength = 15; - var decodedChars = new char[decodeLength]; - var hexPid = new ArrayList(); - for (var i = keyStartIndex; i <= keyEndIndex; i++) - { - hexPid.Add(digitalProductId[i]); - } - for (var i = decodeLength - 1; i >= 0; i--) - { - // Every sixth char is a separator. - if ((i + 1) % 6 == 0) - { - decodedChars[i] = '-'; - } - else - { - // Do the actual decoding. - var digitMapIndex = 0; - for (var j = decodeStringLength - 1; j >= 0; j--) - { - var byteValue = digitMapIndex << 8 | (byte)hexPid[j]; - hexPid[j] = (byte)(byteValue / 24); - digitMapIndex = byteValue % 24; - decodedChars[i] = digits[digitMapIndex]; - } - } - } - return new string(decodedChars); - } - - private static string DecodeProductKeyWin8AndUp(byte[] digitalProductId) - { - var key = string.Empty; - const int keyOffset = 52; - var isWin8 = (byte)(digitalProductId[66] / 6 & 1); - digitalProductId[66] = (byte)(digitalProductId[66] & 0xf7 | (isWin8 & 2) * 4); - - const string digits = "BCDFGHJKMPQRTVWXY2346789"; - var last = 0; - for (var i = 24; i >= 0; i--) - { - var current = 0; - for (var j = 14; j >= 0; j--) - { - current = current * 256; - current = digitalProductId[j + keyOffset] + current; - digitalProductId[j + keyOffset] = (byte)(current / 24); - current = current % 24; - last = current; - } - key = digits[current] + key; - } - - var keypart1 = key.Substring(1, last); - var keypart2 = key.Substring(last + 1, key.Length - (last + 1)); - key = keypart1 + "N" + keypart2; - - for (var i = 5; i < key.Length; i += 6) - { - key = key.Insert(i, "-"); - } - - return key; - } - - private enum DigitalProductIdVersion - { - UpToWindows7, - Windows8AndUp + await sender.SendAsync(GetSystem(), cancellationToken); } } + + private static SystemInfo GetSystem() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select lastbootuptime, localdatetime, numberofprocesses from win32_operatingsystem") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_operatingsystem"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var system = new SystemInfo(); + + using (collection) + { + foreach (ManagementObject @object in collection.Cast()) + { + var properties = @object.GetPropertyHashes(); + + if (@object.TryGetValue(properties, "lastbootuptime", out var lastbootuptime)) + { + system.LastBootUpTime = ManagementDateTimeConverter.ToDateTime(lastbootuptime?.ToString()); + } + + if (@object.TryGetValue(properties, "localdatetime", out var localdatetime)) + { + system.LocalDateTime = ManagementDateTimeConverter.ToDateTime(localdatetime?.ToString()); + } + + system.Processes = @object.GetValue(properties, "numberofprocesses"); + + break; + } + } + + system.License = GetWindowsProductKeyFromRegistry(); + + return system; + } + + private static string GetWindowsProductKeyFromRegistry() + { + var localKey = + RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Environment.Is64BitOperatingSystem + ? RegistryView.Registry64 + : RegistryView.Registry32); + + var registryKeyValue = localKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")?.GetValue("DigitalProductId"); + if (registryKeyValue == null) + return "Failed to get DigitalProductId from registry"; + var digitalProductId = (byte[])registryKeyValue; + localKey.Close(); + var isWin8OrUp = + Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2 + || + Environment.OSVersion.Version.Major > 6; + return GetWindowsProductKeyFromDigitalProductId(digitalProductId, + isWin8OrUp ? DigitalProductIdVersion.Windows8AndUp : DigitalProductIdVersion.UpToWindows7); + } + + private static string GetWindowsProductKeyFromDigitalProductId(byte[] digitalProductId, DigitalProductIdVersion digitalProductIdVersion) + { + + var productKey = digitalProductIdVersion == DigitalProductIdVersion.Windows8AndUp + ? DecodeProductKeyWin8AndUp(digitalProductId) + : DecodeProductKey(digitalProductId); + return productKey; + } + + private static string DecodeProductKey(byte[] digitalProductId) + { + const int keyStartIndex = 52; + const int keyEndIndex = keyStartIndex + 15; + var digits = new[] + { + 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', + 'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9', + }; + const int decodeLength = 29; + const int decodeStringLength = 15; + var decodedChars = new char[decodeLength]; + var hexPid = new ArrayList(); + for (var i = keyStartIndex; i <= keyEndIndex; i++) + { + hexPid.Add(digitalProductId[i]); + } + for (var i = decodeLength - 1; i >= 0; i--) + { + // Every sixth char is a separator. + if ((i + 1) % 6 == 0) + { + decodedChars[i] = '-'; + } + else + { + // Do the actual decoding. + var digitMapIndex = 0; + for (var j = decodeStringLength - 1; j >= 0; j--) + { + var byteValue = digitMapIndex << 8 | (byte)hexPid[j]; + hexPid[j] = (byte)(byteValue / 24); + digitMapIndex = byteValue % 24; + decodedChars[i] = digits[digitMapIndex]; + } + } + } + return new string(decodedChars); + } + + private static string DecodeProductKeyWin8AndUp(byte[] digitalProductId) + { + var key = string.Empty; + const int keyOffset = 52; + var isWin8 = (byte)(digitalProductId[66] / 6 & 1); + digitalProductId[66] = (byte)(digitalProductId[66] & 0xf7 | (isWin8 & 2) * 4); + + const string digits = "BCDFGHJKMPQRTVWXY2346789"; + var last = 0; + for (var i = 24; i >= 0; i--) + { + var current = 0; + for (var j = 14; j >= 0; j--) + { + current = current * 256; + current = digitalProductId[j + keyOffset] + current; + digitalProductId[j + keyOffset] = (byte)(current / 24); + current = current % 24; + last = current; + } + key = digits[current] + key; + } + + var keypart1 = key.Substring(1, last); + var keypart2 = key.Substring(last + 1, key.Length - (last + 1)); + key = keypart1 + "N" + keypart2; + + for (var i = 5; i < key.Length; i += 6) + { + key = key.Insert(i, "-"); + } + + return key; + } + + private enum DigitalProductIdVersion + { + UpToWindows7, + Windows8AndUp + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/UpdateHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/UpdateHandler.cs index 287c181..c90ae74 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/UpdateHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/UpdateHandler.cs @@ -1,130 +1,130 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Runtime.Versioning; using System.Text.RegularExpressions; using WUApiLib; -using static Insight.Agent.Messages.Update; +using static Insight.Domain.Messages.Agent.Update; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class UpdateHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class UpdateHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - await sender.SendAsync(GetUpdates(), cancellationToken); - } - } - - private static UpdateList GetUpdates() - { - return new UpdateList - { - Installed = QueryInstalledUpdates(), - Pending = QueryPendingUpdates() - }; - } - - private static List QueryInstalledUpdates() - { - var updates = new List(); - - var session = new UpdateSessionClass(); - var searcher = session.CreateUpdateSearcher(); - searcher.Online = false; - - var count = searcher.GetTotalHistoryCount(); - var result = searcher.QueryHistory(0, count); - - foreach (IUpdateHistoryEntry wupdate in result) - { - var update = new Update - { - Id = wupdate.UpdateIdentity.UpdateID, - Date = wupdate.Date, - Name = wupdate.Title, - Description = wupdate.Description, - Result = wupdate.ResultCode switch - { - OperationResultCode.orcNotStarted => OsUpdateResultCodeEnum.NotStarted, - OperationResultCode.orcInProgress => OsUpdateResultCodeEnum.InProgress, - OperationResultCode.orcSucceeded => OsUpdateResultCodeEnum.Succeeded, - OperationResultCode.orcSucceededWithErrors => OsUpdateResultCodeEnum.SucceededWithErrors, - OperationResultCode.orcFailed => OsUpdateResultCodeEnum.Failed, - OperationResultCode.orcAborted => OsUpdateResultCodeEnum.Aborted, - _ => null - }, - SupportUrl = wupdate.SupportUrl, - }; - - try - { - var rx = new Regex(@"KB(\d+)"); - update.Hotfix = rx.Match(wupdate.Title).Value; - } - catch (Exception) - { - - } - - updates.Add(update); - } - - return updates; - } - - private static List QueryPendingUpdates() - { - var updates = new List(); - - var session = new UpdateSessionClass(); - var searcher = session.CreateUpdateSearcher(); - searcher.Online = true; - - var result = searcher.Search("IsInstalled=0"); - - foreach (IUpdate wupdate in result.Updates) - { - var update = new Update - { - Id = wupdate.Identity.UpdateID, - Type = wupdate.Type switch - { - UpdateType.utSoftware => OsUpdateTypeEnum.Software, - UpdateType.utDriver => OsUpdateTypeEnum.Driver, - _ => null - }, - Date = wupdate.LastDeploymentChangeTime, - Name = wupdate.Title, - Description = wupdate.Description, - SupportUrl = wupdate.SupportUrl, - Size = wupdate.MaxDownloadSize, - IsDownloaded = wupdate.IsDownloaded, - CanRequestUserInput = wupdate.InstallationBehavior.CanRequestUserInput, - RebootBehavior = wupdate.InstallationBehavior.RebootBehavior switch - { - InstallationRebootBehavior.irbNeverReboots => OsUpdateRebootBehaviorEnum.NeverReboots, - InstallationRebootBehavior.irbAlwaysRequiresReboot => OsUpdateRebootBehaviorEnum.AlwaysRequiresReboot, - InstallationRebootBehavior.irbCanRequestReboot => OsUpdateRebootBehaviorEnum.CanRequestReboot, - _ => null - }, - }; - - if (wupdate.KBArticleIDs.Count > 0) - { - foreach (var id in wupdate.KBArticleIDs) - { - update.Hotfix = $"KB{id}"; - break; - } - } - - updates.Add(update); - } - - return updates; + await sender.SendAsync(GetUpdates(), cancellationToken); } } + + private static UpdateList GetUpdates() + { + return new UpdateList + { + Installed = QueryInstalledUpdates(), + Pending = QueryPendingUpdates() + }; + } + + private static List QueryInstalledUpdates() + { + var updates = new List(); + + var session = new UpdateSessionClass(); + var searcher = session.CreateUpdateSearcher(); + searcher.Online = false; + + var count = searcher.GetTotalHistoryCount(); + var result = searcher.QueryHistory(0, count); + + foreach (IUpdateHistoryEntry wupdate in result) + { + var update = new Update + { + Id = wupdate.UpdateIdentity.UpdateID, + Date = wupdate.Date, + Name = wupdate.Title, + Description = wupdate.Description, + Result = wupdate.ResultCode switch + { + OperationResultCode.orcNotStarted => OsUpdateResultCodeEnum.NotStarted, + OperationResultCode.orcInProgress => OsUpdateResultCodeEnum.InProgress, + OperationResultCode.orcSucceeded => OsUpdateResultCodeEnum.Succeeded, + OperationResultCode.orcSucceededWithErrors => OsUpdateResultCodeEnum.SucceededWithErrors, + OperationResultCode.orcFailed => OsUpdateResultCodeEnum.Failed, + OperationResultCode.orcAborted => OsUpdateResultCodeEnum.Aborted, + _ => null + }, + SupportUrl = wupdate.SupportUrl, + }; + + try + { + var rx = new Regex(@"KB(\d+)"); + update.Hotfix = rx.Match(wupdate.Title).Value; + } + catch (Exception) + { + + } + + updates.Add(update); + } + + return updates; + } + + private static List QueryPendingUpdates() + { + var updates = new List(); + + var session = new UpdateSessionClass(); + var searcher = session.CreateUpdateSearcher(); + searcher.Online = true; + + var result = searcher.Search("IsInstalled=0"); + + foreach (IUpdate wupdate in result.Updates) + { + var update = new Update + { + Id = wupdate.Identity.UpdateID, + Type = wupdate.Type switch + { + UpdateType.utSoftware => OsUpdateTypeEnum.Software, + UpdateType.utDriver => OsUpdateTypeEnum.Driver, + _ => null + }, + Date = wupdate.LastDeploymentChangeTime, + Name = wupdate.Title, + Description = wupdate.Description, + SupportUrl = wupdate.SupportUrl, + Size = wupdate.MaxDownloadSize, + IsDownloaded = wupdate.IsDownloaded, + CanRequestUserInput = wupdate.InstallationBehavior.CanRequestUserInput, + RebootBehavior = wupdate.InstallationBehavior.RebootBehavior switch + { + InstallationRebootBehavior.irbNeverReboots => OsUpdateRebootBehaviorEnum.NeverReboots, + InstallationRebootBehavior.irbAlwaysRequiresReboot => OsUpdateRebootBehaviorEnum.AlwaysRequiresReboot, + InstallationRebootBehavior.irbCanRequestReboot => OsUpdateRebootBehaviorEnum.CanRequestReboot, + _ => null + }, + }; + + if (wupdate.KBArticleIDs.Count > 0) + { + foreach (var id in wupdate.KBArticleIDs) + { + update.Hotfix = $"KB{id}"; + break; + } + } + + updates.Add(update); + } + + return updates; + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/UserHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/UserHandler.cs index b232e3a..98d07fa 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/UserHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/UserHandler.cs @@ -1,188 +1,188 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management; using System.Runtime.Versioning; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class UserHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class UserHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - var result = new UserList(); - result.AddRange(GetUsers()); + var result = new UserList(); + result.AddRange(GetUsers()); - await sender.SendAsync(result, cancellationToken); - } - } - - private static List GetUsers() - { - var users = QueryUsers(); - var groups = GetGroups(); - var usergrouping = QueryUserGroupMaps(); - - foreach (var u in users) - { - u.Groups = new List(); - - foreach (var ug in usergrouping.Where(ug => ug.UserDomain == u.Domain && ug.UserName == u.Name)) - { - var grps = groups.Where(g => g.Domain == ug.GroupDomain && g.Name == ug.GroupName); - - if (grps is not null) - { - u.Groups.AddRange(grps); - } - } - } - - return users; - } - - private static List GetGroups() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select sid, domain, name, description, localaccount from win32_group") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_group"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var groups = new List(); - - using (collection) - { - foreach (ManagementObject @object in collection) - { - var group = new Group(); - - var properties = @object.GetPropertyHashes(); - - group.Sid = @object.GetValue(properties, "sid")?.Trim(); - group.Domain = @object.GetValue(properties, "domain")?.Trim(); - group.Name = @object.GetValue(properties, "name")?.Trim(); - group.Description = @object.GetValue(properties, "description")?.Trim(); - group.LocalAccount = @object.GetValue(properties, "localaccount"); - - groups.Add(group); - } - } - - return groups.OrderBy(x => x.Name)?.ToList(); - } - - private static List QueryUsers() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select sid, name, fullname, description, domain, localaccount, disabled, lockout, status, passwordchangeable, passwordexpires, passwordrequired from win32_useraccount") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_useraccount"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var users = new List(); - - using (collection) - { - foreach (ManagementObject @object in collection) - { - var user = new User(); - - var properties = @object.GetPropertyHashes(); - - user.Sid = @object.GetValue(properties, "sid")?.Trim(); - user.Name = @object.GetValue(properties, "name")?.Trim(); - user.FullName = @object.GetValue(properties, "fullname")?.Trim(); - user.Description = @object.GetValue(properties, "description")?.Trim(); - user.Domain = @object.GetValue(properties, "domain")?.Trim(); - user.LocalAccount = @object.GetValue(properties, "localaccount"); - user.Disabled = @object.GetValue(properties, "disabled"); - user.Lockout = @object.GetValue(properties, "lockout"); - user.Status = @object.GetValue(properties, "status")?.Trim(); - user.PasswordChangeable = @object.GetValue(properties, "passwordchangeable"); - user.PasswordExpires = @object.GetValue(properties, "passwordexpires"); - user.PasswordRequired = @object.GetValue(properties, "passwordrequired"); - - users.Add(user); - } - } - - return users; - } - - private static List QueryUserGroupMaps() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select groupcomponent, partcomponent from win32_groupuser") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_groupuser"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var usergroups = new List(); - - using (collection) - { - foreach (ManagementObject @object in collection) - { - var usergroup = new UserGroupMap(); - - var properties = @object.GetPropertyHashes(); - - var raw = @object.GetValue(properties, "groupcomponent"); - var split = raw?.Split(".Domain=")[1]?.Split(",Name="); - - if (split is not null && split.Length > 1) - { - usergroup.GroupDomain = split[0].TrimStart('"').TrimEnd('"'); - usergroup.GroupName = split[1].TrimStart('"').TrimEnd('"'); - } - - raw = @object.GetValue(properties, "partcomponent"); - split = raw?.Split(".Domain=")[1]?.Split(",Name="); - - if (split is not null && split.Length > 1) - { - usergroup.UserDomain = split[0].TrimStart('"').TrimEnd('"'); - usergroup.UserName = split[1].TrimStart('"').TrimEnd('"'); - } - - usergroups.Add(usergroup); - } - } - - return usergroups; - } - - private class UserGroupMap - { - public string? GroupDomain { get; set; } - public string? GroupName { get; set; } - - public string? UserDomain { get; set; } - public string? UserName { get; set; } + await sender.SendAsync(result, cancellationToken); } } + + private static List GetUsers() + { + var users = QueryUsers(); + var groups = GetGroups(); + var usergrouping = QueryUserGroupMaps(); + + foreach (var u in users) + { + u.Groups = new List(); + + foreach (var ug in usergrouping.Where(ug => ug.UserDomain == u.Domain && ug.UserName == u.Name)) + { + var grps = groups.Where(g => g.Domain == ug.GroupDomain && g.Name == ug.GroupName); + + if (grps is not null) + { + u.Groups.AddRange(grps); + } + } + } + + return users; + } + + private static List GetGroups() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select sid, domain, name, description, localaccount from win32_group") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_group"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var groups = new List(); + + using (collection) + { + foreach (ManagementObject @object in collection) + { + var group = new Group(); + + var properties = @object.GetPropertyHashes(); + + group.Sid = @object.GetValue(properties, "sid")?.Trim(); + group.Domain = @object.GetValue(properties, "domain")?.Trim(); + group.Name = @object.GetValue(properties, "name")?.Trim(); + group.Description = @object.GetValue(properties, "description")?.Trim(); + group.LocalAccount = @object.GetValue(properties, "localaccount"); + + groups.Add(group); + } + } + + return groups.OrderBy(x => x.Name)?.ToList(); + } + + private static List QueryUsers() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select sid, name, fullname, description, domain, localaccount, disabled, lockout, status, passwordchangeable, passwordexpires, passwordrequired from win32_useraccount") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_useraccount"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var users = new List(); + + using (collection) + { + foreach (ManagementObject @object in collection) + { + var user = new User(); + + var properties = @object.GetPropertyHashes(); + + user.Sid = @object.GetValue(properties, "sid")?.Trim(); + user.Name = @object.GetValue(properties, "name")?.Trim(); + user.FullName = @object.GetValue(properties, "fullname")?.Trim(); + user.Description = @object.GetValue(properties, "description")?.Trim(); + user.Domain = @object.GetValue(properties, "domain")?.Trim(); + user.LocalAccount = @object.GetValue(properties, "localaccount"); + user.Disabled = @object.GetValue(properties, "disabled"); + user.Lockout = @object.GetValue(properties, "lockout"); + user.Status = @object.GetValue(properties, "status")?.Trim(); + user.PasswordChangeable = @object.GetValue(properties, "passwordchangeable"); + user.PasswordExpires = @object.GetValue(properties, "passwordexpires"); + user.PasswordRequired = @object.GetValue(properties, "passwordrequired"); + + users.Add(user); + } + } + + return users; + } + + private static List QueryUserGroupMaps() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select groupcomponent, partcomponent from win32_groupuser") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_groupuser"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var usergroups = new List(); + + using (collection) + { + foreach (ManagementObject @object in collection) + { + var usergroup = new UserGroupMap(); + + var properties = @object.GetPropertyHashes(); + + var raw = @object.GetValue(properties, "groupcomponent"); + var split = raw?.Split(".Domain=")[1]?.Split(",Name="); + + if (split is not null && split.Length > 1) + { + usergroup.GroupDomain = split[0].TrimStart('"').TrimEnd('"'); + usergroup.GroupName = split[1].TrimStart('"').TrimEnd('"'); + } + + raw = @object.GetValue(properties, "partcomponent"); + split = raw?.Split(".Domain=")[1]?.Split(",Name="); + + if (split is not null && split.Length > 1) + { + usergroup.UserDomain = split[0].TrimStart('"').TrimEnd('"'); + usergroup.UserName = split[1].TrimStart('"').TrimEnd('"'); + } + + usergroups.Add(usergroup); + } + } + + return usergroups; + } + + private class UserGroupMap + { + public string? GroupDomain { get; set; } + public string? GroupName { get; set; } + + public string? UserDomain { get; set; } + public string? UserName { get; set; } + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/VideocardHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/VideocardHandler.cs index 0e8f1bb..270384b 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/VideocardHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/VideocardHandler.cs @@ -1,64 +1,64 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management; using System.Runtime.Versioning; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class VideocardHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class VideocardHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - var result = new VideocardList(); - result.AddRange(GetVideocards()); + var result = new VideocardList(); + result.AddRange(GetVideocards()); - await sender.SendAsync(result, cancellationToken); - } - } - - private static List GetVideocards() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\cimv2"), - Query = new ObjectQuery("select deviceid, name, adapterram, driverdate, driverversion from win32_videocontroller") - }; - - if (searcher.TryGet(out var collection) is false) - { - searcher.Query = new ObjectQuery("select * from win32_videocontroller"); - - if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var videocards = new List(); - - using (collection) - { - foreach (ManagementObject @object in collection.Cast()) - { - var videocard = new Videocard(); - - var properties = @object.GetPropertyHashes(); - - videocard.DeviceId = @object.GetValue(properties, "deviceid")?.Trim(); - videocard.Model = @object.GetValue(properties, "name")?.Trim(); - - if (@object.TryGetValue(properties, "driverdate", out var driverdate)) - { - videocard.DriverDate = ManagementDateTimeConverter.ToDateTime(driverdate?.ToString()); - } - - videocard.DriverVersion = @object.GetValue(properties, "driverversion")?.Trim(); - - videocards.Add(videocard); - } - } - - return videocards; + await sender.SendAsync(result, cancellationToken); } } + + private static List GetVideocards() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\cimv2"), + Query = new ObjectQuery("select deviceid, name, adapterram, driverdate, driverversion from win32_videocontroller") + }; + + if (searcher.TryGet(out var collection) is false) + { + searcher.Query = new ObjectQuery("select * from win32_videocontroller"); + + if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var videocards = new List(); + + using (collection) + { + foreach (ManagementObject @object in collection.Cast()) + { + var videocard = new Videocard(); + + var properties = @object.GetPropertyHashes(); + + videocard.DeviceId = @object.GetValue(properties, "deviceid")?.Trim(); + videocard.Model = @object.GetValue(properties, "name")?.Trim(); + + if (@object.TryGetValue(properties, "driverdate", out var driverdate)) + { + videocard.DriverDate = ManagementDateTimeConverter.ToDateTime(driverdate?.ToString()); + } + + videocard.DriverVersion = @object.GetValue(properties, "driverversion")?.Trim(); + + videocards.Add(videocard); + } + } + + return videocards; + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Network/Handlers/VirtualMaschineHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/VirtualMaschineHandler.cs index a6cc0ff..98faa5b 100644 --- a/src/Agent/Insight.Agent/Network/Handlers/VirtualMaschineHandler.cs +++ b/src/Agent/Insight.Agent/Network/Handlers/VirtualMaschineHandler.cs @@ -1,359 +1,359 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using System.Management; using System.Runtime.Versioning; -using static Insight.Agent.Messages.VirtualMaschine; -using static Insight.Agent.Messages.VirtualMaschineConfiguration; +using static Insight.Domain.Messages.Agent.VirtualMaschine; +using static Insight.Domain.Messages.Agent.VirtualMaschineConfiguration; -namespace Insight.Agent.Network.Handlers +namespace Insight.Agent.Network.Handlers; + +[SupportedOSPlatform("windows")] +public class VirtualMaschineHandler : IMessageHandler { - [SupportedOSPlatform("windows")] - public class VirtualMaschineHandler : IAgentMessageHandler + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is InventoryRequest) { - if (message is GetInventory) - { - var result = new VirtualMaschineList(); - result.AddRange(GetVirtualMaschines()); + var result = new VirtualMaschineList(); + result.AddRange(GetVirtualMaschines()); - await sender.SendAsync(result, cancellationToken); - } - } - - private static List GetVirtualMaschines() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\virtualization\v2"), - Query = new ObjectQuery("select * msvm_computersystem") - }; - - if (searcher.TryGet(out var computersystems) is false) - { - searcher.Query = new ObjectQuery("select * from msvm_computersystem"); - - if (searcher.TryGet(out computersystems) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var vms = new List(); - - using (computersystems) - { - foreach (ManagementObject cs in computersystems.Cast()) - { - var vm = new VirtualMaschine(); - - var csProperties = cs.GetPropertyHashes(); - - var vmId = cs.GetValue(csProperties, "name")?.Trim(); - - if (Guid.TryParse(vmId, out var vmGuid) is false) continue; - - vm.Id = vmGuid; - vm.ProcessId = cs.GetValue(csProperties, "processid"); - vm.Caption = cs.GetValue(csProperties, "caption")?.Trim(); - vm.Name = cs.GetValue(csProperties, "elementname")?.Trim(); - vm.Enabled = (EnabledEnum)cs.GetValue(csProperties, "enabledstate"); - vm.EnabledDefault = (EnabledDefaultEnum)cs.GetValue(csProperties, "enableddefault"); - vm.HealthState = (HealthStatusEnum)cs.GetValue(csProperties, "healthstate"); - vm.Status = cs.GetValue(csProperties, "status")?.Trim(); - vm.OnTime = cs.GetValue(csProperties, "ontimeinmilliseconds"); - vm.ReplicationMode = cs.GetValue(csProperties, "replicationmode"); - vm.ReplicationState = (ReplicationStateEnum)cs.GetValue(csProperties, "replicationstate"); - vm.ReplicationHealth = (ReplicationHealthEnum)cs.GetValue(csProperties, "replicationhealth"); - - if (cs.TryGetValue(csProperties, "installdate", out var installdate)) - { - vm.InstallDate = ManagementDateTimeConverter.ToDateTime(installdate?.ToString()); - } - - if (cs.TryGetValue(csProperties, "timeoflastconfigurationchange", out var timeoflastconfigurationchange)) - { - vm.TimeOfLastConfigurationChange = ManagementDateTimeConverter.ToDateTime(timeoflastconfigurationchange?.ToString()); - } - - if (cs.TryGetValue(csProperties, "timeoflaststatechange", out var timeoflaststatechange)) - { - vm.TimeOfLastStateChange = ManagementDateTimeConverter.ToDateTime(timeoflaststatechange?.ToString()); - } - - if (cs.TryGetValue(csProperties, "lastreplicationtime", out var lastreplicationtime)) - { - vm.LastReplicationTime = ManagementDateTimeConverter.ToDateTime(lastreplicationtime?.ToString()); - } - - var summaryinformation = cs.GetRelated("msvm_summaryinformation"); - using (summaryinformation) - { - foreach (ManagementObject si in summaryinformation.Cast()) - { - var siProperties = si.GetPropertyHashes(); - - vm.Notes = si.GetValue(siProperties, "Notes"); - vm.ConfigurationVersion = si.GetValue(siProperties, "Version"); - vm.IntegrationServicesVersionState = (IntegrationServicesVersionStateEnum)si.GetValue(siProperties, "IntegrationServicesVersionState"); - vm.GuestOperatingSystem = si.GetValue(siProperties, "GuestOperatingSystem"); - vm.NumberOfProcessors = si.GetValue(siProperties, "NumberOfProcessors"); - vm.ProcessorLoad = si.GetValue(siProperties, "ProcessorLoad"); - vm.MemoryAvailable = si.GetValue(siProperties, "MemoryAvailable"); - vm.MemoryUsage = si.GetValue(siProperties, "MemoryUsage"); - } - } - - var virtualSystemSettingData = cs.GetRelated("Msvm_VirtualSystemSettingData"); - using (virtualSystemSettingData) - { - var configs = new List(); - - foreach (ManagementObject vssd in virtualSystemSettingData.Cast()) - { - var vmc = new VirtualMaschineConfiguration(); - - var vssdProperties = vssd.GetPropertyHashes(); - - var vmcId = vssd.GetValue(vssdProperties, "ConfigurationID")?.Trim(); - - if (Guid.TryParse(vmcId, out var vmcGuid) is false) continue; - - vmc.Id = vmcGuid.ToString(); - - vmc.Type = vssd.GetValue(vssdProperties, "VirtualSystemType"); - vmc.Name = vssd.GetValue(vssdProperties, "ElementName"); - - if (vssd.TryGetValue(vssdProperties, "CreationTime", out var creationtime)) - { - vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(creationtime?.ToString()); - } - - vmc.Generation = vssd.GetValue(vssdProperties, "VirtualSystemSubType"); - vmc.Architecture = vssd.GetValue(vssdProperties, "Architecture"); - vmc.AutomaticStartupAction = (AutomaticStartupActionEnum)vssd.GetValue(vssdProperties, "AutomaticStartupAction"); - vmc.AutomaticShutdownAction = (AutomaticShutdownActionEnum)vssd.GetValue(vssdProperties, "AutomaticShutdownAction"); - vmc.AutomaticRecoveryAction = (AutomaticRecoveryActionEnum)vssd.GetValue(vssdProperties, "AutomaticRecoveryAction"); - vmc.AutomaticSnapshotsEnabled = vssd.GetValue(vssdProperties, "AutomaticSnapshotsEnabled"); - - //if (vssd.TryGetValue(vssdProperties, "AutomaticStartupActionDelay", out var automaticstartupactiondelay)) - //{ - // vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(automaticstartupactiondelay?.ToString()); - //} - - vmc.BaseBoardSerialNumber = vssd.GetValue(vssdProperties, "BaseBoardSerialNumber"); - vmc.BIOSGUID = vssd.GetValue(vssdProperties, "BIOSGUID"); - vmc.BIOSSerialNumber = vssd.GetValue(vssdProperties, "BIOSSerialNumber"); - vmc.BootOrder = vssd.GetValue(vssdProperties, "BootOrder"); - vmc.ConfigurationDataRoot = vssd.GetValue(vssdProperties, "ConfigurationDataRoot"); - vmc.ConfigurationFile = vssd.GetValue(vssdProperties, "ConfigurationFile"); - vmc.GuestStateDataRoot = vssd.GetValue(vssdProperties, "GuestStateDataRoot"); - vmc.GuestStateFile = vssd.GetValue(vssdProperties, "GuestStateFile"); - vmc.SnapshotDataRoot = vssd.GetValue(vssdProperties, "SnapshotDataRoot"); - vmc.SuspendDataRoot = vssd.GetValue(vssdProperties, "SuspendDataRoot"); - vmc.SwapFileDataRoot = vssd.GetValue(vssdProperties, "SwapFileDataRoot"); - vmc.SecureBootEnabled = vssd.GetValue(vssdProperties, "SecureBootEnabled"); - vmc.IsAutomaticSnapshot = vssd.GetValue(vssdProperties, "IsAutomaticSnapshot"); - vmc.Notes = vssd.GetValue(vssdProperties, "Notes"); - - if (vssd.GetValue(vssdProperties, "Parent") is string parent) - { - using var vmcp = new ManagementObject(parent); - vmcp.Get(); - - if (Guid.TryParse(vmcp["ConfigurationID"]?.ToString(), out var parentGuid) is false) continue; - vmc.ParentId = parentGuid.ToString(); - } - - //var storageallocationsettingdata = cs.GetRelated("Msvm_StorageAllocationSettingData"); - //using (storageallocationsettingdata) - //{ - - //} - - configs.Add(vmc); - } - - vm.Configurations = configs.GroupBy(p => p.Id).Select(p => p.First()).ToList(); - } - - vms.Add(vm); - } - } - - return vms; - } - - private static List QueryVirtualMaschines0() - { - using var searcher = new ManagementObjectSearcher - { - Scope = new ManagementScope(@"root\virtualization\v2"), - Query = new ObjectQuery("select * msvm_computersystem") - }; - - if (searcher.TryGet(out var computersystems) is false) - { - searcher.Query = new ObjectQuery("select * from msvm_computersystem"); - - if (searcher.TryGet(out computersystems) is false) throw new InvalidOperationException("WMI Collection NULL"); - } - - var vms = new List(); - - using (computersystems) - { - foreach (ManagementObject cs in computersystems.Cast()) - { - var vm = new VirtualMaschine(); - - var csProperties = cs.GetPropertyHashes(); - - var vmId = cs.GetValue(csProperties, "name")?.Trim(); - - if (Guid.TryParse(vmId, out var vmGuid) is false) continue; - - vm.Id = vmGuid; - vm.ProcessId = cs.GetValue(csProperties, "processid"); - vm.Caption = cs.GetValue(csProperties, "caption")?.Trim(); - vm.Name = cs.GetValue(csProperties, "elementname")?.Trim(); - vm.Enabled = (EnabledEnum)cs.GetValue(csProperties, "enabledstate"); - vm.EnabledDefault = (EnabledDefaultEnum)cs.GetValue(csProperties, "enableddefault"); - vm.HealthState = (HealthStatusEnum)cs.GetValue(csProperties, "healthstate"); - vm.Status = cs.GetValue(csProperties, "status")?.Trim(); - vm.OnTime = cs.GetValue(csProperties, "ontimeinmilliseconds"); - vm.ReplicationMode = cs.GetValue(csProperties, "replicationmode"); - vm.ReplicationState = (ReplicationStateEnum)cs.GetValue(csProperties, "replicationstate"); - vm.ReplicationHealth = (ReplicationHealthEnum)cs.GetValue(csProperties, "replicationhealth"); - - if (cs.TryGetValue(csProperties, "installdate", out var installdate)) - { - vm.InstallDate = ManagementDateTimeConverter.ToDateTime(installdate?.ToString()); - } - - if (cs.TryGetValue(csProperties, "timeoflastconfigurationchange", out var timeoflastconfigurationchange)) - { - vm.TimeOfLastConfigurationChange = ManagementDateTimeConverter.ToDateTime(timeoflastconfigurationchange?.ToString()); - } - - if (cs.TryGetValue(csProperties, "timeoflaststatechange", out var timeoflaststatechange)) - { - vm.TimeOfLastStateChange = ManagementDateTimeConverter.ToDateTime(timeoflaststatechange?.ToString()); - } - - if (cs.TryGetValue(csProperties, "lastreplicationtime", out var lastreplicationtime)) - { - vm.LastReplicationTime = ManagementDateTimeConverter.ToDateTime(lastreplicationtime?.ToString()); - } - - var summaryinformation = cs.GetRelated("msvm_summaryinformation"); - using (summaryinformation) - { - foreach (ManagementObject si in summaryinformation.Cast()) - { - var siProperties = si.GetPropertyHashes(); - - vm.Notes = si.GetValue(siProperties, "Notes"); - vm.ConfigurationVersion = si.GetValue(siProperties, "Version"); - vm.IntegrationServicesVersionState = (IntegrationServicesVersionStateEnum)si.GetValue(siProperties, "IntegrationServicesVersionState"); - vm.GuestOperatingSystem = si.GetValue(siProperties, "GuestOperatingSystem"); - vm.NumberOfProcessors = si.GetValue(siProperties, "NumberOfProcessors"); - vm.ProcessorLoad = si.GetValue(siProperties, "ProcessorLoad"); - vm.MemoryAvailable = si.GetValue(siProperties, "MemoryAvailable"); - vm.MemoryUsage = si.GetValue(siProperties, "MemoryUsage"); - } - } - - var virtualSystemSettingData = cs.GetRelated("Msvm_VirtualSystemSettingData"); - using (virtualSystemSettingData) - { - var configs = new List(); - - foreach (ManagementObject vssd in virtualSystemSettingData.Cast()) - { - var vmc = new VirtualMaschineConfiguration(); - - var vssdProperties = vssd.GetPropertyHashes(); - - var vmcId = vssd.GetValue(vssdProperties, "ConfigurationID")?.Trim(); - - if (Guid.TryParse(vmcId, out var vmcGuid) is false) continue; - - vmc.Id = vmcGuid.ToString(); - - vmc.Type = vssd.GetValue(vssdProperties, "VirtualSystemType"); - vmc.Name = vssd.GetValue(vssdProperties, "ElementName"); - - if (vssd.TryGetValue(vssdProperties, "CreationTime", out var creationtime)) - { - vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(creationtime?.ToString()); - } - - vmc.Generation = vssd.GetValue(vssdProperties, "VirtualSystemSubType"); - vmc.Architecture = vssd.GetValue(vssdProperties, "Architecture"); - vmc.AutomaticStartupAction = (AutomaticStartupActionEnum)vssd.GetValue(vssdProperties, "AutomaticStartupAction"); - - //if (vssd.TryGetValue(vssdProperties, "AutomaticStartupActionDelay", out var automaticstartupactiondelay)) - //{ - // vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(automaticstartupactiondelay?.ToString()); - //} - - vmc.AutomaticShutdownAction = (AutomaticShutdownActionEnum)vssd.GetValue(vssdProperties, "AutomaticShutdownAction"); - vmc.AutomaticRecoveryAction = (AutomaticRecoveryActionEnum)vssd.GetValue(vssdProperties, "AutomaticRecoveryAction"); - vmc.AutomaticSnapshotsEnabled = vssd.GetValue(vssdProperties, "AutomaticSnapshotsEnabled"); - - vmc.BaseBoardSerialNumber = vssd.GetValue(vssdProperties, "BaseBoardSerialNumber"); - vmc.BIOSGUID = vssd.GetValue(vssdProperties, "BIOSGUID"); - vmc.BIOSSerialNumber = vssd.GetValue(vssdProperties, "BIOSSerialNumber"); - vmc.BootOrder = vssd.GetValue(vssdProperties, "BootOrder"); - vmc.ConfigurationDataRoot = vssd.GetValue(vssdProperties, "ConfigurationDataRoot"); - vmc.ConfigurationFile = vssd.GetValue(vssdProperties, "ConfigurationFile"); - vmc.GuestStateDataRoot = vssd.GetValue(vssdProperties, "GuestStateDataRoot"); - vmc.GuestStateFile = vssd.GetValue(vssdProperties, "GuestStateFile"); - vmc.SnapshotDataRoot = vssd.GetValue(vssdProperties, "SnapshotDataRoot"); - vmc.SuspendDataRoot = vssd.GetValue(vssdProperties, "SuspendDataRoot"); - vmc.SwapFileDataRoot = vssd.GetValue(vssdProperties, "SwapFileDataRoot"); - vmc.SecureBootEnabled = vssd.GetValue(vssdProperties, "SecureBootEnabled"); - vmc.IsAutomaticSnapshot = vssd.GetValue(vssdProperties, "IsAutomaticSnapshot"); - vmc.Notes = vssd.GetValue(vssdProperties, "Notes"); - vmc.ParentId = vssd.GetValue(vssdProperties, "Parent"); - - var storageallocationsettingdata = cs.GetRelated("Msvm_StorageAllocationSettingData"); - using (storageallocationsettingdata) - { - - } - - configs.Add(vmc); - } - - configs = configs.GroupBy(p => p.Id).Select(p => p.First()).ToList(); - if (configs.Any(p => p.ParentId is not null)) - { - foreach (var conf in configs.Where(p => p.ParentId is not null)) - { - using var parent = new ManagementObject(conf.ParentId); - parent.Get(); - - if (Guid.TryParse(parent["ConfigurationID"]?.ToString(), out var parentGuid) && configs.FirstOrDefault(p => p.Id == parentGuid.ToString()) is VirtualMaschineConfiguration parentConfig) - { - conf.ParentId = parentGuid.ToString(); - - parentConfig.Childs ??= new List(); - parentConfig.Childs.Add(conf); - } - else - { - conf.ParentId = null; - } - } - } - - vm.Configurations = configs.Where(p => p.ParentId is null).ToList(); - } - - vms.Add(vm); - } - } - - return vms; + await sender.SendAsync(result, cancellationToken); } } + + private static List GetVirtualMaschines() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\virtualization\v2"), + Query = new ObjectQuery("select * msvm_computersystem") + }; + + if (searcher.TryGet(out var computersystems) is false) + { + searcher.Query = new ObjectQuery("select * from msvm_computersystem"); + + if (searcher.TryGet(out computersystems) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var vms = new List(); + + using (computersystems) + { + foreach (ManagementObject cs in computersystems.Cast()) + { + var vm = new VirtualMaschine(); + + var csProperties = cs.GetPropertyHashes(); + + var vmId = cs.GetValue(csProperties, "name")?.Trim(); + + if (Guid.TryParse(vmId, out var vmGuid) is false) continue; + + vm.Id = vmGuid; + vm.ProcessId = cs.GetValue(csProperties, "processid"); + vm.Caption = cs.GetValue(csProperties, "caption")?.Trim(); + vm.Name = cs.GetValue(csProperties, "elementname")?.Trim(); + vm.Enabled = (EnabledEnum)cs.GetValue(csProperties, "enabledstate"); + vm.EnabledDefault = (EnabledDefaultEnum)cs.GetValue(csProperties, "enableddefault"); + vm.HealthState = (HealthStatusEnum)cs.GetValue(csProperties, "healthstate"); + vm.Status = cs.GetValue(csProperties, "status")?.Trim(); + vm.OnTime = cs.GetValue(csProperties, "ontimeinmilliseconds"); + vm.ReplicationMode = cs.GetValue(csProperties, "replicationmode"); + vm.ReplicationState = (ReplicationStateEnum)cs.GetValue(csProperties, "replicationstate"); + vm.ReplicationHealth = (ReplicationHealthEnum)cs.GetValue(csProperties, "replicationhealth"); + + if (cs.TryGetValue(csProperties, "installdate", out var installdate)) + { + vm.InstallDate = ManagementDateTimeConverter.ToDateTime(installdate?.ToString()); + } + + if (cs.TryGetValue(csProperties, "timeoflastconfigurationchange", out var timeoflastconfigurationchange)) + { + vm.TimeOfLastConfigurationChange = ManagementDateTimeConverter.ToDateTime(timeoflastconfigurationchange?.ToString()); + } + + if (cs.TryGetValue(csProperties, "timeoflaststatechange", out var timeoflaststatechange)) + { + vm.TimeOfLastStateChange = ManagementDateTimeConverter.ToDateTime(timeoflaststatechange?.ToString()); + } + + if (cs.TryGetValue(csProperties, "lastreplicationtime", out var lastreplicationtime)) + { + vm.LastReplicationTime = ManagementDateTimeConverter.ToDateTime(lastreplicationtime?.ToString()); + } + + var summaryinformation = cs.GetRelated("msvm_summaryinformation"); + using (summaryinformation) + { + foreach (ManagementObject si in summaryinformation.Cast()) + { + var siProperties = si.GetPropertyHashes(); + + vm.Notes = si.GetValue(siProperties, "Notes"); + vm.ConfigurationVersion = si.GetValue(siProperties, "Version"); + vm.IntegrationServicesVersionState = (IntegrationServicesVersionStateEnum)si.GetValue(siProperties, "IntegrationServicesVersionState"); + vm.GuestOperatingSystem = si.GetValue(siProperties, "GuestOperatingSystem"); + vm.NumberOfProcessors = si.GetValue(siProperties, "NumberOfProcessors"); + vm.ProcessorLoad = si.GetValue(siProperties, "ProcessorLoad"); + vm.MemoryAvailable = si.GetValue(siProperties, "MemoryAvailable"); + vm.MemoryUsage = si.GetValue(siProperties, "MemoryUsage"); + } + } + + var virtualSystemSettingData = cs.GetRelated("Msvm_VirtualSystemSettingData"); + using (virtualSystemSettingData) + { + var configs = new List(); + + foreach (ManagementObject vssd in virtualSystemSettingData.Cast()) + { + var vmc = new VirtualMaschineConfiguration(); + + var vssdProperties = vssd.GetPropertyHashes(); + + var vmcId = vssd.GetValue(vssdProperties, "ConfigurationID")?.Trim(); + + if (Guid.TryParse(vmcId, out var vmcGuid) is false) continue; + + vmc.Id = vmcGuid.ToString(); + + vmc.Type = vssd.GetValue(vssdProperties, "VirtualSystemType"); + vmc.Name = vssd.GetValue(vssdProperties, "ElementName"); + + if (vssd.TryGetValue(vssdProperties, "CreationTime", out var creationtime)) + { + vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(creationtime?.ToString()); + } + + vmc.Generation = vssd.GetValue(vssdProperties, "VirtualSystemSubType"); + vmc.Architecture = vssd.GetValue(vssdProperties, "Architecture"); + vmc.AutomaticStartupAction = (AutomaticStartupActionEnum)vssd.GetValue(vssdProperties, "AutomaticStartupAction"); + vmc.AutomaticShutdownAction = (AutomaticShutdownActionEnum)vssd.GetValue(vssdProperties, "AutomaticShutdownAction"); + vmc.AutomaticRecoveryAction = (AutomaticRecoveryActionEnum)vssd.GetValue(vssdProperties, "AutomaticRecoveryAction"); + vmc.AutomaticSnapshotsEnabled = vssd.GetValue(vssdProperties, "AutomaticSnapshotsEnabled"); + + //if (vssd.TryGetValue(vssdProperties, "AutomaticStartupActionDelay", out var automaticstartupactiondelay)) + //{ + // vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(automaticstartupactiondelay?.ToString()); + //} + + vmc.BaseBoardSerialNumber = vssd.GetValue(vssdProperties, "BaseBoardSerialNumber"); + vmc.BIOSGUID = vssd.GetValue(vssdProperties, "BIOSGUID"); + vmc.BIOSSerialNumber = vssd.GetValue(vssdProperties, "BIOSSerialNumber"); + vmc.BootOrder = vssd.GetValue(vssdProperties, "BootOrder"); + vmc.ConfigurationDataRoot = vssd.GetValue(vssdProperties, "ConfigurationDataRoot"); + vmc.ConfigurationFile = vssd.GetValue(vssdProperties, "ConfigurationFile"); + vmc.GuestStateDataRoot = vssd.GetValue(vssdProperties, "GuestStateDataRoot"); + vmc.GuestStateFile = vssd.GetValue(vssdProperties, "GuestStateFile"); + vmc.SnapshotDataRoot = vssd.GetValue(vssdProperties, "SnapshotDataRoot"); + vmc.SuspendDataRoot = vssd.GetValue(vssdProperties, "SuspendDataRoot"); + vmc.SwapFileDataRoot = vssd.GetValue(vssdProperties, "SwapFileDataRoot"); + vmc.SecureBootEnabled = vssd.GetValue(vssdProperties, "SecureBootEnabled"); + vmc.IsAutomaticSnapshot = vssd.GetValue(vssdProperties, "IsAutomaticSnapshot"); + vmc.Notes = vssd.GetValue(vssdProperties, "Notes"); + + if (vssd.GetValue(vssdProperties, "Parent") is string parent) + { + using var vmcp = new ManagementObject(parent); + vmcp.Get(); + + if (Guid.TryParse(vmcp["ConfigurationID"]?.ToString(), out var parentGuid) is false) continue; + vmc.ParentId = parentGuid.ToString(); + } + + //var storageallocationsettingdata = cs.GetRelated("Msvm_StorageAllocationSettingData"); + //using (storageallocationsettingdata) + //{ + + //} + + configs.Add(vmc); + } + + vm.Configurations = configs.GroupBy(p => p.Id).Select(p => p.First()).ToList(); + } + + vms.Add(vm); + } + } + + return vms; + } + + private static List QueryVirtualMaschines0() + { + using var searcher = new ManagementObjectSearcher + { + Scope = new ManagementScope(@"root\virtualization\v2"), + Query = new ObjectQuery("select * msvm_computersystem") + }; + + if (searcher.TryGet(out var computersystems) is false) + { + searcher.Query = new ObjectQuery("select * from msvm_computersystem"); + + if (searcher.TryGet(out computersystems) is false) throw new InvalidOperationException("WMI Collection NULL"); + } + + var vms = new List(); + + using (computersystems) + { + foreach (ManagementObject cs in computersystems.Cast()) + { + var vm = new VirtualMaschine(); + + var csProperties = cs.GetPropertyHashes(); + + var vmId = cs.GetValue(csProperties, "name")?.Trim(); + + if (Guid.TryParse(vmId, out var vmGuid) is false) continue; + + vm.Id = vmGuid; + vm.ProcessId = cs.GetValue(csProperties, "processid"); + vm.Caption = cs.GetValue(csProperties, "caption")?.Trim(); + vm.Name = cs.GetValue(csProperties, "elementname")?.Trim(); + vm.Enabled = (EnabledEnum)cs.GetValue(csProperties, "enabledstate"); + vm.EnabledDefault = (EnabledDefaultEnum)cs.GetValue(csProperties, "enableddefault"); + vm.HealthState = (HealthStatusEnum)cs.GetValue(csProperties, "healthstate"); + vm.Status = cs.GetValue(csProperties, "status")?.Trim(); + vm.OnTime = cs.GetValue(csProperties, "ontimeinmilliseconds"); + vm.ReplicationMode = cs.GetValue(csProperties, "replicationmode"); + vm.ReplicationState = (ReplicationStateEnum)cs.GetValue(csProperties, "replicationstate"); + vm.ReplicationHealth = (ReplicationHealthEnum)cs.GetValue(csProperties, "replicationhealth"); + + if (cs.TryGetValue(csProperties, "installdate", out var installdate)) + { + vm.InstallDate = ManagementDateTimeConverter.ToDateTime(installdate?.ToString()); + } + + if (cs.TryGetValue(csProperties, "timeoflastconfigurationchange", out var timeoflastconfigurationchange)) + { + vm.TimeOfLastConfigurationChange = ManagementDateTimeConverter.ToDateTime(timeoflastconfigurationchange?.ToString()); + } + + if (cs.TryGetValue(csProperties, "timeoflaststatechange", out var timeoflaststatechange)) + { + vm.TimeOfLastStateChange = ManagementDateTimeConverter.ToDateTime(timeoflaststatechange?.ToString()); + } + + if (cs.TryGetValue(csProperties, "lastreplicationtime", out var lastreplicationtime)) + { + vm.LastReplicationTime = ManagementDateTimeConverter.ToDateTime(lastreplicationtime?.ToString()); + } + + var summaryinformation = cs.GetRelated("msvm_summaryinformation"); + using (summaryinformation) + { + foreach (ManagementObject si in summaryinformation.Cast()) + { + var siProperties = si.GetPropertyHashes(); + + vm.Notes = si.GetValue(siProperties, "Notes"); + vm.ConfigurationVersion = si.GetValue(siProperties, "Version"); + vm.IntegrationServicesVersionState = (IntegrationServicesVersionStateEnum)si.GetValue(siProperties, "IntegrationServicesVersionState"); + vm.GuestOperatingSystem = si.GetValue(siProperties, "GuestOperatingSystem"); + vm.NumberOfProcessors = si.GetValue(siProperties, "NumberOfProcessors"); + vm.ProcessorLoad = si.GetValue(siProperties, "ProcessorLoad"); + vm.MemoryAvailable = si.GetValue(siProperties, "MemoryAvailable"); + vm.MemoryUsage = si.GetValue(siProperties, "MemoryUsage"); + } + } + + var virtualSystemSettingData = cs.GetRelated("Msvm_VirtualSystemSettingData"); + using (virtualSystemSettingData) + { + var configs = new List(); + + foreach (ManagementObject vssd in virtualSystemSettingData.Cast()) + { + var vmc = new VirtualMaschineConfiguration(); + + var vssdProperties = vssd.GetPropertyHashes(); + + var vmcId = vssd.GetValue(vssdProperties, "ConfigurationID")?.Trim(); + + if (Guid.TryParse(vmcId, out var vmcGuid) is false) continue; + + vmc.Id = vmcGuid.ToString(); + + vmc.Type = vssd.GetValue(vssdProperties, "VirtualSystemType"); + vmc.Name = vssd.GetValue(vssdProperties, "ElementName"); + + if (vssd.TryGetValue(vssdProperties, "CreationTime", out var creationtime)) + { + vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(creationtime?.ToString()); + } + + vmc.Generation = vssd.GetValue(vssdProperties, "VirtualSystemSubType"); + vmc.Architecture = vssd.GetValue(vssdProperties, "Architecture"); + vmc.AutomaticStartupAction = (AutomaticStartupActionEnum)vssd.GetValue(vssdProperties, "AutomaticStartupAction"); + + //if (vssd.TryGetValue(vssdProperties, "AutomaticStartupActionDelay", out var automaticstartupactiondelay)) + //{ + // vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(automaticstartupactiondelay?.ToString()); + //} + + vmc.AutomaticShutdownAction = (AutomaticShutdownActionEnum)vssd.GetValue(vssdProperties, "AutomaticShutdownAction"); + vmc.AutomaticRecoveryAction = (AutomaticRecoveryActionEnum)vssd.GetValue(vssdProperties, "AutomaticRecoveryAction"); + vmc.AutomaticSnapshotsEnabled = vssd.GetValue(vssdProperties, "AutomaticSnapshotsEnabled"); + + vmc.BaseBoardSerialNumber = vssd.GetValue(vssdProperties, "BaseBoardSerialNumber"); + vmc.BIOSGUID = vssd.GetValue(vssdProperties, "BIOSGUID"); + vmc.BIOSSerialNumber = vssd.GetValue(vssdProperties, "BIOSSerialNumber"); + vmc.BootOrder = vssd.GetValue(vssdProperties, "BootOrder"); + vmc.ConfigurationDataRoot = vssd.GetValue(vssdProperties, "ConfigurationDataRoot"); + vmc.ConfigurationFile = vssd.GetValue(vssdProperties, "ConfigurationFile"); + vmc.GuestStateDataRoot = vssd.GetValue(vssdProperties, "GuestStateDataRoot"); + vmc.GuestStateFile = vssd.GetValue(vssdProperties, "GuestStateFile"); + vmc.SnapshotDataRoot = vssd.GetValue(vssdProperties, "SnapshotDataRoot"); + vmc.SuspendDataRoot = vssd.GetValue(vssdProperties, "SuspendDataRoot"); + vmc.SwapFileDataRoot = vssd.GetValue(vssdProperties, "SwapFileDataRoot"); + vmc.SecureBootEnabled = vssd.GetValue(vssdProperties, "SecureBootEnabled"); + vmc.IsAutomaticSnapshot = vssd.GetValue(vssdProperties, "IsAutomaticSnapshot"); + vmc.Notes = vssd.GetValue(vssdProperties, "Notes"); + vmc.ParentId = vssd.GetValue(vssdProperties, "Parent"); + + var storageallocationsettingdata = cs.GetRelated("Msvm_StorageAllocationSettingData"); + using (storageallocationsettingdata) + { + + } + + configs.Add(vmc); + } + + configs = configs.GroupBy(p => p.Id).Select(p => p.First()).ToList(); + if (configs.Any(p => p.ParentId is not null)) + { + foreach (var conf in configs.Where(p => p.ParentId is not null)) + { + using var parent = new ManagementObject(conf.ParentId); + parent.Get(); + + if (Guid.TryParse(parent["ConfigurationID"]?.ToString(), out var parentGuid) && configs.FirstOrDefault(p => p.Id == parentGuid.ToString()) is VirtualMaschineConfiguration parentConfig) + { + conf.ParentId = parentGuid.ToString(); + + parentConfig.Childs ??= new List(); + parentConfig.Childs.Add(conf); + } + else + { + conf.ParentId = null; + } + } + } + + vm.Configurations = configs.Where(p => p.ParentId is null).ToList(); + } + + vms.Add(vm); + } + } + + return vms; + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Program.cs b/src/Agent/Insight.Agent/Program.cs index 005cb9e..e102bae 100644 --- a/src/Agent/Insight.Agent/Program.cs +++ b/src/Agent/Insight.Agent/Program.cs @@ -1,10 +1,10 @@ using Insight.Agent.Extensions; -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; using Insight.Agent.Network; using Insight.Agent.Network.Handlers; using Insight.Agent.Services; using Insight.Domain.Constants; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -12,86 +12,85 @@ using Microsoft.Extensions.Logging; using Vaitr.Network; 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); + builder.UseWindowsService(); + builder.UseSystemd(); + + builder.ConfigureAppConfiguration(config => { - var builder = Host.CreateDefaultBuilder(args); - builder.UseWindowsService(); - builder.UseSystemd(); + config.Defaults(); + }); - builder.ConfigureAppConfiguration(config => + builder.ConfigureLogging(options => + { + options.ClearProviders(); + options.SetMinimumLevel(LogLevel.Trace); + + options.AddSimpleConsole(options => { - config.Defaults(); + options.IncludeScopes = true; + options.SingleLine = true; + options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff "; }); - builder.ConfigureLogging(options => + 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) => + { + // SERVICES + services.AddHostedService(); + services.AddHostedService(); + + // SERVICES (WINDOWS) + if (OperatingSystem.IsWindows()) services.AddHostedService(); + + // AGENT NETWORKING + services.UseHostedClient(options => { - options.ClearProviders(); - options.SetMinimumLevel(LogLevel.Trace); + options.Host = host.Configuration.GetValue(Appsettings.ServerHost) ?? throw new Exception($"{Appsettings.ServerHost} value not set (appsettings)"); + options.Port = host.Configuration.GetValue(Appsettings.ServerPort) ?? throw new Exception($"{Appsettings.ServerPort} value not set (appsettings)"); + options.Keepalive = 10000; + options.Timeout = 30000; + options.Encryption = Encryption.Tls12; - options.AddSimpleConsole(options => - { - options.IncludeScopes = true; - options.SingleLine = true; - options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff "; - }); - - options.AddFile($"{Configuration.AppDirectory?.FullName}/" + "logs/agent_{Date}.log", LogLevel.Trace, fileSizeLimitBytes: 104857600, retainedFileCountLimit: 10, outputTemplate: "{Timestamp:o} [{Level:u3}] {Message} {NewLine}{Exception}"); + options.UseSerializer, IMessage>(); }); - builder.ConfigureServices((host, services) => + services.AddSingleton, AuthenticationHandler>(); + services.AddSingleton, DriveHandler>(); + services.AddSingleton, InterfaceHandler>(); + services.AddSingleton, MainboardHandler>(); + services.AddSingleton, MemoryHandler>(); + services.AddSingleton, OperationSystemHandler>(); + services.AddSingleton, PrinterHandler>(); + services.AddSingleton, ProcessorHandler>(); + services.AddSingleton, ServiceHandler>(); + services.AddSingleton, SessionHandler>(); + services.AddSingleton, SoftwareHandler>(); + services.AddSingleton, StoragePoolHandler>(); + services.AddSingleton, SystemInfoHandler>(); + services.AddSingleton, UpdateHandler>(); + services.AddSingleton, UserHandler>(); + services.AddSingleton, VideocardHandler>(); + services.AddSingleton, VirtualMaschineHandler>(); + services.AddSingleton, ConsoleHandler>(); + + // GLOBAL DEPENDENCIES + services.AddTransient(provider => new HttpClient(new HttpClientHandler { - // SERVICES - services.AddHostedService(); - services.AddHostedService(); + ClientCertificateOptions = ClientCertificateOption.Manual, + ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => true + })); + }); - // SERVICES (WINDOWS) - if (OperatingSystem.IsWindows()) services.AddHostedService(); - - // AGENT NETWORKING - services.UseHostedClient(options => - { - options.Host = host.Configuration.GetValue(Appsettings.ServerHost) ?? throw new Exception($"{Appsettings.ServerHost} value not set (appsettings)"); - options.Port = host.Configuration.GetValue(Appsettings.ServerPort) ?? throw new Exception($"{Appsettings.ServerPort} value not set (appsettings)"); - options.Keepalive = 10000; - options.Timeout = 30000; - options.Encryption = Encryption.Tls12; - - options.UseSerializer, IAgentMessage>(); - }); - - services.AddSingleton, AuthenticationHandler>(); - services.AddSingleton, DriveHandler>(); - services.AddSingleton, InterfaceHandler>(); - services.AddSingleton, MainboardHandler>(); - services.AddSingleton, MemoryHandler>(); - services.AddSingleton, OperationSystemHandler>(); - services.AddSingleton, PrinterHandler>(); - services.AddSingleton, ProcessorHandler>(); - services.AddSingleton, ServiceHandler>(); - services.AddSingleton, SessionHandler>(); - services.AddSingleton, SoftwareHandler>(); - services.AddSingleton, StoragePoolHandler>(); - services.AddSingleton, SystemInfoHandler>(); - services.AddSingleton, UpdateHandler>(); - services.AddSingleton, UserHandler>(); - services.AddSingleton, VideocardHandler>(); - services.AddSingleton, VirtualMaschineHandler>(); - services.AddSingleton, ConsoleHandler>(); - - // GLOBAL DEPENDENCIES - services.AddTransient(provider => new HttpClient(new HttpClientHandler - { - ClientCertificateOptions = ClientCertificateOption.Manual, - ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => true - })); - }); - - var host = builder.Build(); - await host.RunAsync().ConfigureAwait(false); - } + var host = builder.Build(); + await host.RunAsync().ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Services/EventService.cs b/src/Agent/Insight.Agent/Services/EventService.cs index 95a56e1..5499c18 100644 --- a/src/Agent/Insight.Agent/Services/EventService.cs +++ b/src/Agent/Insight.Agent/Services/EventService.cs @@ -1,170 +1,170 @@ -using Insight.Agent.Messages; -using Insight.Agent.Network; +using Insight.Agent.Network; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Diagnostics.Eventing.Reader; using System.Runtime.Versioning; using System.Threading.Channels; using Vaitr.Network; -using static Insight.Agent.Messages.Event; +using static Insight.Domain.Messages.Agent.Event; 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 _queue; + private readonly ISessionPool _pool; + private readonly ILogger _logger; + + public EventService(ISessionPool pool, ILogger logger) { - private readonly Channel _queue; - private readonly ISessionPool _pool; - private readonly ILogger _logger; + _pool = pool; + _logger = logger; - public EventService(ISessionPool pool, ILogger logger) + _queue = Channel.CreateBounded(new BoundedChannelOptions(1000) { - _pool = pool; - _logger = logger; + SingleReader = true, + SingleWriter = true, + AllowSynchronousContinuations = false, + FullMode = BoundedChannelFullMode.DropOldest + }); + } - _queue = Channel.CreateBounded(new BoundedChannelOptions(1000) - { - SingleReader = true, - SingleWriter = true, - AllowSynchronousContinuations = false, - FullMode = BoundedChannelFullMode.DropOldest - }); - } + protected override async Task ExecuteAsync(CancellationToken cancellationToken) + { + _logger.LogTrace("ExecuteAsync"); - protected override async Task ExecuteAsync(CancellationToken cancellationToken) + while (cancellationToken.IsCancellationRequested is false) { - _logger.LogTrace("ExecuteAsync"); - - while (cancellationToken.IsCancellationRequested is false) - { - try - { - var tasks = new List - { - HandleQueueAsync(cancellationToken), - WatchAsync("Application", "*", cancellationToken), - WatchAsync("Security", "*", cancellationToken), - WatchAsync("System", "*", cancellationToken), - WatchAsync("Microsoft-Windows-PrintService/Admin", "*", cancellationToken), - WatchAsync("Microsoft-Windows-TaskScheduler/Operational", "*", cancellationToken), - WatchAsync("Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational", "*", cancellationToken), - WatchAsync("Microsoft-Windows-TerminalServices-LocalSessionManager/Operational", "*", cancellationToken), - WatchAsync("Microsoft-Windows-TerminalServices-RDPClient/Operational", "*", cancellationToken), - WatchAsync("Microsoft-Windows-SmbClient/Connectivity", "*", cancellationToken), - WatchAsync("Microsoft-Windows-SmbClient/Security", "*", cancellationToken), - WatchAsync("Microsoft-Windows-SMBServer/Security", "*", cancellationToken), - WatchAsync("Microsoft-Windows-StorageSpaces-Driver/Operational", "*", cancellationToken), - WatchAsync("Microsoft-Windows-Diagnostics-Performance/Operational", "*", cancellationToken) - }; - - await Task.WhenAll(tasks); - } - catch (OperationCanceledException) { } - catch (Exception ex) - { - _logger.LogError("{ex}", ex); - } - } - } - - private async Task WatchAsync(string path, string query, CancellationToken cancellationToken) - { - var config = new EventLogConfiguration(path); - if (config is null) return; - - if (config.IsEnabled is false) - { - config.IsEnabled = true; - config.SaveChanges(); - } - - var watcher = new EventLogWatcher(new EventLogQuery(path, PathType.LogName, query) - { - TolerateQueryErrors = true, - Session = EventLogSession.GlobalSession - }); - try { - watcher.EventRecordWritten += new EventHandler(OnEvent); - watcher.Enabled = true; - - using var semaphore = new SemaphoreSlim(0, 1); - await semaphore.WaitAsync(cancellationToken); - } - catch (Exception) { } - finally - { - watcher.EventRecordWritten -= new EventHandler(OnEvent); - watcher.Enabled = false; - - watcher?.Dispose(); - } - } - - private async Task HandleQueueAsync(CancellationToken cancellationToken) - { - while (await _queue.Reader.WaitToReadAsync(cancellationToken)) - { - var session = _pool.FirstOrDefault(); - - if (session.Value is null) + var tasks = new List { - await Task.Delay(10000, cancellationToken); - continue; - } - - if (_queue.Reader.TryRead(out var item) is false) - { - await Task.Delay(1000, cancellationToken); - continue; - } - - try - { - await session.Value.SendAsync(item, cancellationToken); - } - catch (OperationCanceledException) { } - catch (Exception ex) - { - _logger.LogError("{ex}", ex); - await Task.Delay(10000, cancellationToken); - } - } - } - - private void OnEvent(object? sender, EventRecordWrittenEventArgs e) - { - if (e is null || e.EventRecord is null) return; - - try - { - var @event = new Event - { - Timestamp = e?.EventRecord?.TimeCreated, - EventId = e?.EventRecord?.Id, - Source = e?.EventRecord?.ProviderName, - Category = e?.EventRecord?.LogName, - Task = e?.EventRecord?.TaskDisplayName, - Message = e?.EventRecord?.FormatDescription(), + HandleQueueAsync(cancellationToken), + WatchAsync("Application", "*", cancellationToken), + WatchAsync("Security", "*", cancellationToken), + WatchAsync("System", "*", cancellationToken), + WatchAsync("Microsoft-Windows-PrintService/Admin", "*", cancellationToken), + WatchAsync("Microsoft-Windows-TaskScheduler/Operational", "*", cancellationToken), + WatchAsync("Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational", "*", cancellationToken), + WatchAsync("Microsoft-Windows-TerminalServices-LocalSessionManager/Operational", "*", cancellationToken), + WatchAsync("Microsoft-Windows-TerminalServices-RDPClient/Operational", "*", cancellationToken), + WatchAsync("Microsoft-Windows-SmbClient/Connectivity", "*", cancellationToken), + WatchAsync("Microsoft-Windows-SmbClient/Security", "*", cancellationToken), + WatchAsync("Microsoft-Windows-SMBServer/Security", "*", cancellationToken), + WatchAsync("Microsoft-Windows-StorageSpaces-Driver/Operational", "*", cancellationToken), + WatchAsync("Microsoft-Windows-Diagnostics-Performance/Operational", "*", cancellationToken) }; - if (e?.EventRecord?.Level is not null) - { - @event.Status = (EventLevel)Convert.ToInt32(e?.EventRecord?.Level) switch - { - EventLevel.Informational => StatusType.Information, - EventLevel.Warning => StatusType.Warning, - EventLevel.Error => StatusType.Error, - EventLevel.Critical => StatusType.Critical, - _ => StatusType.Information, - }; - } - - _queue.Writer.WriteAsync(@event, default); + await Task.WhenAll(tasks); + } + catch (OperationCanceledException) { } + catch (Exception ex) + { + _logger.LogError("{ex}", ex); } - catch (Exception) { } // app crash } } + + private async Task WatchAsync(string path, string query, CancellationToken cancellationToken) + { + var config = new EventLogConfiguration(path); + if (config is null) return; + + if (config.IsEnabled is false) + { + config.IsEnabled = true; + config.SaveChanges(); + } + + var watcher = new EventLogWatcher(new EventLogQuery(path, PathType.LogName, query) + { + TolerateQueryErrors = true, + Session = EventLogSession.GlobalSession + }); + + try + { + watcher.EventRecordWritten += new EventHandler(OnEvent); + watcher.Enabled = true; + + using var semaphore = new SemaphoreSlim(0, 1); + await semaphore.WaitAsync(cancellationToken); + } + catch (Exception) { } + finally + { + watcher.EventRecordWritten -= new EventHandler(OnEvent); + watcher.Enabled = false; + + watcher?.Dispose(); + } + } + + private async Task HandleQueueAsync(CancellationToken cancellationToken) + { + while (await _queue.Reader.WaitToReadAsync(cancellationToken)) + { + var session = _pool.FirstOrDefault(); + + if (session.Value is null) + { + await Task.Delay(10000, cancellationToken); + continue; + } + + if (_queue.Reader.TryRead(out var item) is false) + { + await Task.Delay(1000, cancellationToken); + continue; + } + + try + { + await session.Value.SendAsync(item, cancellationToken); + } + catch (OperationCanceledException) { } + catch (Exception ex) + { + _logger.LogError("{ex}", ex); + await Task.Delay(10000, cancellationToken); + } + } + } + + private void OnEvent(object? sender, EventRecordWrittenEventArgs e) + { + if (e is null || e.EventRecord is null) return; + + try + { + var @event = new Event + { + Timestamp = e?.EventRecord?.TimeCreated, + EventId = e?.EventRecord?.Id, + Source = e?.EventRecord?.ProviderName, + Category = e?.EventRecord?.LogName, + Task = e?.EventRecord?.TaskDisplayName, + Message = e?.EventRecord?.FormatDescription(), + }; + + if (e?.EventRecord?.Level is not null) + { + @event.Status = (EventLevel)Convert.ToInt32(e?.EventRecord?.Level) switch + { + EventLevel.Informational => StatusType.Information, + EventLevel.Warning => StatusType.Warning, + EventLevel.Error => StatusType.Error, + EventLevel.Critical => StatusType.Critical, + _ => StatusType.Information, + }; + } + + _queue.Writer.WriteAsync(@event, default); + } + catch (Exception) { } // app crash + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Services/TrapService.cs b/src/Agent/Insight.Agent/Services/TrapService.cs index b386e7f..8e95054 100644 --- a/src/Agent/Insight.Agent/Services/TrapService.cs +++ b/src/Agent/Insight.Agent/Services/TrapService.cs @@ -1,5 +1,6 @@ -using Insight.Agent.Messages; -using Insight.Agent.Network; +using Insight.Agent.Network; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -9,192 +10,190 @@ using System.Net.Sockets; using System.Threading.Channels; 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 readonly Channel _queue; + + private readonly int _port; + private readonly ISessionPool _pool; + private readonly ILogger _logger; + + public TrapService(ISessionPool pool, IConfiguration configuration, ILogger logger) { - private static IPEndPoint EndpointCache { get; } = new(IPAddress.Any, 0); - private readonly Channel _queue; + _port = configuration.GetValue(Appsettings.TrapPort) ?? throw new Exception($"{Appsettings.TrapPort} value not set (appsettings)"); + _pool = pool; + _logger = logger; - - private readonly int _port; - private readonly ISessionPool _pool; - private readonly ILogger _logger; - - public TrapService(ISessionPool pool, IConfiguration configuration, ILogger logger) + _queue = Channel.CreateBounded(new BoundedChannelOptions(100) { - _port = configuration.GetValue(Appsettings.TrapPort) ?? throw new Exception($"{Appsettings.TrapPort} value not set (appsettings)"); - _pool = pool; - _logger = logger; + SingleReader = false, + SingleWriter = true, + AllowSynchronousContinuations = false, + FullMode = BoundedChannelFullMode.DropOldest + }); + } - _queue = Channel.CreateBounded(new BoundedChannelOptions(100) - { - SingleReader = false, - SingleWriter = true, - AllowSynchronousContinuations = false, - FullMode = BoundedChannelFullMode.DropOldest - }); - } + protected override async Task ExecuteAsync(CancellationToken cancellationToken) + { + _logger.LogTrace("ExecuteAsync"); - protected override async Task ExecuteAsync(CancellationToken cancellationToken) + while (cancellationToken.IsCancellationRequested is false) { - _logger.LogTrace("ExecuteAsync"); - - while (cancellationToken.IsCancellationRequested is false) - { - try - { - var tasks = new List - { - HandleQueueAsync(cancellationToken), - ListenAsync(cancellationToken) - }; - - await Task.WhenAll(tasks); - } - catch (OperationCanceledException) { } - catch (Exception ex) - { - _logger.LogError("{ex}", ex); - } - } - } - - private async Task HandleQueueAsync(CancellationToken cancellationToken) - { - while (await _queue.Reader.WaitToReadAsync(cancellationToken)) - { - var session = _pool.FirstOrDefault(); - - if (session.Value is null) - { - await Task.Delay(10000, cancellationToken); - continue; - } - - if (_queue.Reader.TryRead(out var item) is false) - { - await Task.Delay(1000, cancellationToken); - continue; - } - - try - { - await session.Value.SendAsync(item, cancellationToken); - } - catch (OperationCanceledException) { } - catch (Exception ex) - { - _logger.LogError("{ex}", ex); - await Task.Delay(10000, cancellationToken); - } - } - } - - private async Task ListenAsync(CancellationToken cancellationToken) - { - using var udpSocket = new Socket(SocketType.Dgram, ProtocolType.Udp); - - cancellationToken.Register(udpSocket.Dispose); - - udpSocket.Bind(new IPEndPoint(IPAddress.Any, _port)); - - var buffer = GC.AllocateArray(length: 65527, pinned: true); - var bufferMem = buffer.AsMemory(); - - while (cancellationToken.IsCancellationRequested is false) - { - try - { - var result = await udpSocket.ReceiveFromAsync(bufferMem, SocketFlags.None, EndpointCache, cancellationToken); - - if (result.ReceivedBytes == 0) continue; - - var actualBytes = bufferMem[..result.ReceivedBytes].ToArray(); - - var ep = (IPEndPoint)result.RemoteEndPoint; - - await ProcessAsync(ep, actualBytes, cancellationToken); - } - catch (SocketException) { continue; } - catch (IOException) { continue; } - catch (Exception) { continue; } - } - } - - private async ValueTask ProcessAsync(IPEndPoint endpoint, byte[] buffer, CancellationToken cancellationToken) - { - var trap = new Trap - { - Timestamp = DateTime.Now, - Endpoint = endpoint.ToString(), - }; - try { - var protocol = (SnmpVersion)SnmpPacket.GetProtocolVersion(buffer, buffer.Length); - - trap.Version = protocol.ToString(); - trap.Hostname = Dns.GetHostEntry(endpoint.Address)?.HostName; - - if (protocol == SnmpVersion.Ver1) + var tasks = new List { - var packet = new SnmpV1TrapPacket(); - packet.decode(buffer, buffer.Length); + HandleQueueAsync(cancellationToken), + ListenAsync(cancellationToken) + }; - trap.Community = packet?.Community?.ToString(); - - if (packet?.Pdu?.VbList is not null) - { - trap.Data = ConvertVbs(packet.Pdu.VbList); - } - } - - if (protocol == SnmpVersion.Ver2) - { - var packet = new SnmpV2Packet(); - packet.decode(buffer, buffer.Length); - - trap.Community = packet?.Community?.ToString(); - - if (packet?.Pdu?.VbList is not null) - { - trap.Data = ConvertVbs(packet.Pdu.VbList); - } - } - - if (protocol == SnmpVersion.Ver3) - { - var packet = new SnmpV3Packet(); - } + await Task.WhenAll(tasks); } + catch (OperationCanceledException) { } catch (Exception ex) { _logger.LogError("{ex}", ex); } - - await _queue.Writer.WriteAsync(trap, cancellationToken); - } - - private List>? ConvertVbs(VbCollection vbs) - { - var data = new List>(); - - try - { - foreach (var item in vbs) - { - if (item.Oid is null) continue; - - data.Add(new KeyValuePair(item.Oid.ToString(), item?.Value?.ToString())); - } - } - catch (Exception ex) - { - _logger.LogError("{ex}", ex); - } - - return data; } } + + private async Task HandleQueueAsync(CancellationToken cancellationToken) + { + while (await _queue.Reader.WaitToReadAsync(cancellationToken)) + { + var session = _pool.FirstOrDefault(); + + if (session.Value is null) + { + await Task.Delay(10000, cancellationToken); + continue; + } + + if (_queue.Reader.TryRead(out var item) is false) + { + await Task.Delay(1000, cancellationToken); + continue; + } + + try + { + await session.Value.SendAsync(item, cancellationToken); + } + catch (OperationCanceledException) { } + catch (Exception ex) + { + _logger.LogError("{ex}", ex); + await Task.Delay(10000, cancellationToken); + } + } + } + + private async Task ListenAsync(CancellationToken cancellationToken) + { + using var udpSocket = new Socket(SocketType.Dgram, ProtocolType.Udp); + + cancellationToken.Register(udpSocket.Dispose); + + udpSocket.Bind(new IPEndPoint(IPAddress.Any, _port)); + + var buffer = GC.AllocateArray(length: 65527, pinned: true); + var bufferMem = buffer.AsMemory(); + + while (cancellationToken.IsCancellationRequested is false) + { + try + { + var result = await udpSocket.ReceiveFromAsync(bufferMem, SocketFlags.None, EndpointCache, cancellationToken); + + if (result.ReceivedBytes == 0) continue; + + var actualBytes = bufferMem[..result.ReceivedBytes].ToArray(); + + var ep = (IPEndPoint)result.RemoteEndPoint; + + await ProcessAsync(ep, actualBytes, cancellationToken); + } + catch (SocketException) { continue; } + catch (IOException) { continue; } + catch (Exception) { continue; } + } + } + + private async ValueTask ProcessAsync(IPEndPoint endpoint, byte[] buffer, CancellationToken cancellationToken) + { + var trap = new Trap + { + Timestamp = DateTime.Now, + Endpoint = endpoint.ToString(), + }; + + try + { + var protocol = (SnmpVersion)SnmpPacket.GetProtocolVersion(buffer, buffer.Length); + + trap.Version = protocol.ToString(); + trap.Hostname = Dns.GetHostEntry(endpoint.Address)?.HostName; + + if (protocol == SnmpVersion.Ver1) + { + var packet = new SnmpV1TrapPacket(); + packet.decode(buffer, buffer.Length); + + trap.Community = packet?.Community?.ToString(); + + if (packet?.Pdu?.VbList is not null) + { + trap.Data = ConvertVbs(packet.Pdu.VbList); + } + } + + if (protocol == SnmpVersion.Ver2) + { + var packet = new SnmpV2Packet(); + packet.decode(buffer, buffer.Length); + + trap.Community = packet?.Community?.ToString(); + + if (packet?.Pdu?.VbList is not null) + { + trap.Data = ConvertVbs(packet.Pdu.VbList); + } + } + + if (protocol == SnmpVersion.Ver3) + { + var packet = new SnmpV3Packet(); + } + } + catch (Exception ex) + { + _logger.LogError("{ex}", ex); + } + + await _queue.Writer.WriteAsync(trap, cancellationToken); + } + + private List>? ConvertVbs(VbCollection vbs) + { + var data = new List>(); + + try + { + foreach (var item in vbs) + { + if (item.Oid is null) continue; + + data.Add(new KeyValuePair(item.Oid.ToString(), item?.Value?.ToString())); + } + } + catch (Exception ex) + { + _logger.LogError("{ex}", ex); + } + + return data; + } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Services/UpdateService.cs b/src/Agent/Insight.Agent/Services/UpdateService.cs index 6869d58..f879069 100644 --- a/src/Agent/Insight.Agent/Services/UpdateService.cs +++ b/src/Agent/Insight.Agent/Services/UpdateService.cs @@ -10,351 +10,350 @@ using System.Runtime.Versioning; using System.ServiceProcess; using System.Text.Json; -namespace Insight.Agent.Services +namespace Insight.Agent.Services; + +internal class UpdateService : BackgroundService { - internal class UpdateService : BackgroundService + private readonly Uri _uri; + + private readonly HttpClient _httpClient; + private readonly ILogger _logger; + + public UpdateService(HttpClient httpClient, IConfiguration configuration, ILogger logger) { - private readonly Uri _uri; + _httpClient = httpClient; + _uri = configuration.GetValue("api") ?? throw new Exception($"api value not set (appsettings)"); + _logger = logger; + } - private readonly HttpClient _httpClient; - private readonly ILogger _logger; + protected override async Task ExecuteAsync(CancellationToken cancellationToken) + { + _logger.LogTrace("ExecuteAsync"); - public UpdateService(HttpClient httpClient, IConfiguration configuration, ILogger logger) + while (cancellationToken.IsCancellationRequested is false) { - _httpClient = httpClient; - _uri = configuration.GetValue("api") ?? throw new Exception($"api value not set (appsettings)"); - _logger = logger; + try + { + UpdateResult? result = null; + + if (OperatingSystem.IsWindows()) result = await WindowsUpdateAsync(cancellationToken); + if (OperatingSystem.IsLinux()) result = await LinuxUpdateAsync(cancellationToken); + + _logger.LogInformation("Update Result: {result}", result?.Success); + if (result?.UpdateErrors is not null) + { + _logger.LogError("Update Errors: {errors}", string.Concat(result?.UpdateErrors)); + } + } + catch (OperationCanceledException) { } + catch (Exception ex) // may inform via client / api about errors + { + _logger.LogError("{ex}", ex.Message); + } + finally + { + await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken); + } } + } - protected override async Task ExecuteAsync(CancellationToken cancellationToken) + [SupportedOSPlatform("windows")] + private async ValueTask WindowsUpdateAsync(CancellationToken cancellationToken) + { + return await Windows.Service.UpdateAsync( + _httpClient, + Deploy.GetUpdateHref(_uri, Deploy.Updater.Name), + Deploy.GetAppExecutable(Deploy.Updater.Name), + Deploy.Updater.ServiceName, + cancellationToken); + } + + [SupportedOSPlatform("linux")] + private ValueTask LinuxUpdateAsync(CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } + + [SupportedOSPlatform("windows")] + private static class Windows + { + public static class Service { - _logger.LogTrace("ExecuteAsync"); - - while (cancellationToken.IsCancellationRequested is false) + public static bool ServiceExistence(string serviceName) { try { - UpdateResult? result = null; + if (ServiceController.GetServices().Any(s => s.ServiceName.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase))) return true; + return false; + } + catch (Exception) { } - if (OperatingSystem.IsWindows()) result = await WindowsUpdateAsync(cancellationToken); - if (OperatingSystem.IsLinux()) result = await LinuxUpdateAsync(cancellationToken); - - _logger.LogInformation("Update Result: {result}", result?.Success); - if (result?.UpdateErrors is not null) - { - _logger.LogError("Update Errors: {errors}", string.Concat(result?.UpdateErrors)); - } - } - catch (OperationCanceledException) { } - catch (Exception ex) // may inform via client / api about errors - { - _logger.LogError("{ex}", ex.Message); - } - finally - { - await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken); - } + return false; } - } - [SupportedOSPlatform("windows")] - private async ValueTask WindowsUpdateAsync(CancellationToken cancellationToken) - { - return await Windows.Service.UpdateAsync( - _httpClient, - Deploy.GetUpdateHref(_uri, Deploy.Updater.Name), - Deploy.GetAppExecutable(Deploy.Updater.Name), - Deploy.Updater.ServiceName, - cancellationToken); - } - - [SupportedOSPlatform("linux")] - private ValueTask LinuxUpdateAsync(CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } - - [SupportedOSPlatform("windows")] - private static class Windows - { - public static class Service + public static bool SetServiceState(string app, ServiceControllerStatus status, TimeSpan timeout) { - public static bool ServiceExistence(string serviceName) + try { - try + using var sc = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName.Equals(app, StringComparison.InvariantCultureIgnoreCase)); + if (sc is null) return false; + + if (sc.Status != status) { - if (ServiceController.GetServices().Any(s => s.ServiceName.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase))) return true; - return false; + switch (status) + { + case ServiceControllerStatus.Running: + sc.Start(); + break; + + case ServiceControllerStatus.Stopped: + sc.Stop(); + break; + } + + sc.WaitForStatus(status, timeout); } - catch (Exception) { } - return false; + return true; } + catch (Exception) { } - public static bool SetServiceState(string app, ServiceControllerStatus status, TimeSpan timeout) + return false; + } + + public static async ValueTask UpdateAsync(HttpClient httpClient, Uri api, FileInfo bin, string serviceName, CancellationToken cancellationToken) + { + var result = new UpdateResult { - try + Api = api?.ToString(), + SourceDirectory = bin.Directory?.FullName, + App = bin.Name, + ServiceName = serviceName + }; + + try + { + // check if service exists + if (ServiceExistence(serviceName) is false) { - using var sc = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName.Equals(app, StringComparison.InvariantCultureIgnoreCase)); - if (sc is null) return false; - - if (sc.Status != status) - { - switch (status) - { - case ServiceControllerStatus.Running: - sc.Start(); - break; - - case ServiceControllerStatus.Stopped: - sc.Stop(); - break; - } - - sc.WaitForStatus(status, timeout); - } - - return true; + result.UpdateErrors.Add("service not found"); + return result; } - catch (Exception) { } - return false; - } - - public static async ValueTask UpdateAsync(HttpClient httpClient, Uri api, FileInfo bin, string serviceName, CancellationToken cancellationToken) - { - var result = new UpdateResult + // get service update details + var response = await httpClient.GetFromJsonAsync(api, cancellationToken); + if (response is null) { - Api = api?.ToString(), - SourceDirectory = bin.Directory?.FullName, - App = bin.Name, - ServiceName = serviceName - }; + result.ApiErrors.Add("not available / response null"); + return result; + } - try + result.ApiAvailable = true; + + // check if local binary exists + if (bin is null) { - // check if service exists - if (ServiceExistence(serviceName) is false) - { - result.UpdateErrors.Add("service not found"); - return result; - } + result.UpdateErrors.Add("source binary not found"); + return result; + } - // get service update details - var response = await httpClient.GetFromJsonAsync(api, cancellationToken); - if (response is null) - { - result.ApiErrors.Add("not available / response null"); - return result; - } - - result.ApiAvailable = true; - - // check if local binary exists - if (bin is null) - { - result.UpdateErrors.Add("source binary not found"); - return result; - } - - // get local file binary version - if (FileVersionInfo.GetVersionInfo(bin.FullName).FileVersion is not string binVersionString) - { - result.UpdateErrors.Add("source binary fileversion not valid"); - return result; - } - - // compare local against update version, skip lower or equal update version - var actualVersion = Version.Parse(binVersionString); - if (actualVersion >= response.Version) - { - result.Success = true; - return result; - } - else - { - result.UpdateAvailable = true; - } - - // get update file (bytes) to memory - using var update = await httpClient.GetAsync(response.Uri, cancellationToken); - if (update is null) - { - result.ApiErrors.Add("update source not available"); - return result; - } - - // stop service - if (SetServiceState(serviceName, ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)) is false) - { - result.UpdateErrors.Add("service control failed / failed to stop service"); - return result; - } - - // read update archive to temp (overwrite) - var temp = Directory.CreateTempSubdirectory(); - var updateFile = new FileInfo($@"{temp.FullName}/{bin.Name}.zip"); - - await File.WriteAllBytesAsync(updateFile.FullName, await update.Content.ReadAsByteArrayAsync(cancellationToken), cancellationToken); - - // extract update archive from temp to app dir (overwrite) - ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory?.FullName, true); - - // delete temp folder - if (temp.Exists) temp.Delete(true); - - // start updateds service - if (SetServiceState(serviceName, ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)) is false) - { - result.UpdateErrors.Add("service control failed / failed to start service"); - return result; - } + // get local file binary version + if (FileVersionInfo.GetVersionInfo(bin.FullName).FileVersion is not string binVersionString) + { + result.UpdateErrors.Add("source binary fileversion not valid"); + return result; + } + // compare local against update version, skip lower or equal update version + var actualVersion = Version.Parse(binVersionString); + if (actualVersion >= response.Version) + { result.Success = true; + return result; } - catch (Exception ex) + else { - result.UpdateErrors.Add(ex.Message); + result.UpdateAvailable = true; } - return result; + // get update file (bytes) to memory + using var update = await httpClient.GetAsync(response.Uri, cancellationToken); + if (update is null) + { + result.ApiErrors.Add("update source not available"); + return result; + } + + // stop service + if (SetServiceState(serviceName, ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)) is false) + { + result.UpdateErrors.Add("service control failed / failed to stop service"); + return result; + } + + // read update archive to temp (overwrite) + var temp = Directory.CreateTempSubdirectory(); + var updateFile = new FileInfo($@"{temp.FullName}/{bin.Name}.zip"); + + await File.WriteAllBytesAsync(updateFile.FullName, await update.Content.ReadAsByteArrayAsync(cancellationToken), cancellationToken); + + // extract update archive from temp to app dir (overwrite) + ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory?.FullName, true); + + // delete temp folder + if (temp.Exists) temp.Delete(true); + + // start updateds service + if (SetServiceState(serviceName, ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)) is false) + { + result.UpdateErrors.Add("service control failed / failed to start service"); + return result; + } + + result.Success = true; } + catch (Exception ex) + { + result.UpdateErrors.Add(ex.Message); + } + + return result; + } + } + + public static class Process + { + public static bool IsRunning(FileInfo bin) + { + if (bin.Exists is false) return false; + + var matched = System.Diagnostics.Process.GetProcessesByName(bin.FullName); + + if (matched is null || matched.Any() is false) return false; + + if (matched.Any(p => + p.MainModule is not null && + p.MainModule.FileName is not null && + p.MainModule.FileName.Equals(bin.FullName, + StringComparison.InvariantCultureIgnoreCase))) return true; + + return false; } - public static class Process + public static bool Start(FileInfo binary) { - public static bool IsRunning(FileInfo bin) + try { - if (bin.Exists is false) return false; + if (IsRunning(binary) is false) return false; - var matched = System.Diagnostics.Process.GetProcessesByName(bin.FullName); - - if (matched is null || matched.Any() is false) return false; - - if (matched.Any(p => - p.MainModule is not null && - p.MainModule.FileName is not null && - p.MainModule.FileName.Equals(bin.FullName, - StringComparison.InvariantCultureIgnoreCase))) return true; - - return false; + using var process = System.Diagnostics.Process.Start(binary.FullName); + return true; } + catch (Exception) { } - public static bool Start(FileInfo binary) - { - try - { - if (IsRunning(binary) is false) return false; + return false; + } - using var process = System.Diagnostics.Process.Start(binary.FullName); - return true; - } - catch (Exception) { } - - return false; - } - - public static bool Stop(FileInfo bin, TimeSpan timeout) - { - try - { - if (IsRunning(bin) is false) return false; - - var matched = System.Diagnostics.Process.GetProcessesByName(bin.FullName); - - if (matched is null || matched.Any() is false) return true; - - foreach (var procsInfo in matched.Where(p => - p.MainModule is not null && - p.MainModule.FileName is not null && - p.MainModule.FileName.Equals(bin.FullName, StringComparison.InvariantCultureIgnoreCase))) - { - if (procsInfo.CloseMainWindow()) procsInfo.WaitForExit((int)timeout.TotalMilliseconds); - if (procsInfo.HasExited is false) procsInfo.Kill(true); - } - - return true; - } - catch (Exception) { } - - return false; - } - - public static async ValueTask UpdateAsync(HttpClient httpClient, Uri api, FileInfo bin, CancellationToken cancellationToken) + public static bool Stop(FileInfo bin, TimeSpan timeout) + { + try { if (IsRunning(bin) is false) return false; - var response = await httpClient.GetFromJsonAsync(api.AbsoluteUri, new JsonSerializerOptions + var matched = System.Diagnostics.Process.GetProcessesByName(bin.FullName); + + if (matched is null || matched.Any() is false) return true; + + foreach (var procsInfo in matched.Where(p => + p.MainModule is not null && + p.MainModule.FileName is not null && + p.MainModule.FileName.Equals(bin.FullName, StringComparison.InvariantCultureIgnoreCase))) { - IncludeFields = true - }, cancellationToken); - - if (response is null) return false; - - Version actualVersion; - - if (FileVersionInfo.GetVersionInfo(bin.FullName).FileVersion is not string binVersionString) return false; - - try - { - actualVersion = Version.Parse(binVersionString); - if (actualVersion >= response.Version) return false; - - using var update = await httpClient.GetAsync(response.Uri, cancellationToken); - if (update is null) return false; - - Stop(bin, TimeSpan.FromSeconds(60)); - - // read update archive to temp (overwrite) - var temp = Directory.CreateTempSubdirectory(); - var updateFile = new FileInfo($@"{temp.FullName}/{bin.Name}.zip"); - - await File.WriteAllBytesAsync(updateFile.FullName, await update.Content.ReadAsByteArrayAsync(cancellationToken), cancellationToken); - - // extract update archive from temp to app dir (overwrite) - ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory?.FullName, true); - - // delete temp folder - if (temp.Exists) temp.Delete(true); - - // rewrite with options to start user session process - //Start(app, directory, TimeSpan.FromSeconds(60)); - - return true; + if (procsInfo.CloseMainWindow()) procsInfo.WaitForExit((int)timeout.TotalMilliseconds); + if (procsInfo.HasExited is false) procsInfo.Kill(true); } - catch (Exception) { } - return false; + return true; } + catch (Exception) { } - public static bool Delete(FileInfo bin, TimeSpan timeout) + return false; + } + + public static async ValueTask UpdateAsync(HttpClient httpClient, Uri api, FileInfo bin, CancellationToken cancellationToken) + { + if (IsRunning(bin) is false) return false; + + var response = await httpClient.GetFromJsonAsync(api.AbsoluteUri, new JsonSerializerOptions { - try - { - Stop(bin, timeout); - bin.Delete(); + IncludeFields = true + }, cancellationToken); - return true; - } - catch (Exception) { } + if (response is null) return false; - return false; + Version actualVersion; + + if (FileVersionInfo.GetVersionInfo(bin.FullName).FileVersion is not string binVersionString) return false; + + try + { + actualVersion = Version.Parse(binVersionString); + if (actualVersion >= response.Version) return false; + + using var update = await httpClient.GetAsync(response.Uri, cancellationToken); + if (update is null) return false; + + Stop(bin, TimeSpan.FromSeconds(60)); + + // read update archive to temp (overwrite) + var temp = Directory.CreateTempSubdirectory(); + var updateFile = new FileInfo($@"{temp.FullName}/{bin.Name}.zip"); + + await File.WriteAllBytesAsync(updateFile.FullName, await update.Content.ReadAsByteArrayAsync(cancellationToken), cancellationToken); + + // extract update archive from temp to app dir (overwrite) + ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory?.FullName, true); + + // delete temp folder + if (temp.Exists) temp.Delete(true); + + // rewrite with options to start user session process + //Start(app, directory, TimeSpan.FromSeconds(60)); + + return true; } + catch (Exception) { } + + return false; + } + + public static bool Delete(FileInfo bin, TimeSpan timeout) + { + try + { + Stop(bin, timeout); + bin.Delete(); + + return true; + } + catch (Exception) { } + + return false; } } + } - public class UpdateResult - { - public string? Api { get; set; } - public string? SourceDirectory { get; set; } - public string? App { get; set; } - public string? ServiceName { get; set; } + public class UpdateResult + { + public string? Api { get; set; } + public string? SourceDirectory { get; set; } + public string? App { get; set; } + public string? ServiceName { get; set; } - public bool ApiAvailable { get; set; } = false; - public bool UpdateAvailable { get; set; } = false; - public bool Success { get; set; } = false; - public List ApiErrors { get; } = new(); - public List UpdateErrors { get; } = new(); - } + public bool ApiAvailable { get; set; } = false; + public bool UpdateAvailable { get; set; } = false; + public bool Success { get; set; } = false; + public List ApiErrors { get; } = new(); + public List UpdateErrors { get; } = new(); } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Services/_Collector/_Os.cs b/src/Agent/Insight.Agent/Services/_Collector/_Os.cs index 7b3eb0e..3caa4b2 100644 --- a/src/Agent/Insight.Agent/Services/_Collector/_Os.cs +++ b/src/Agent/Insight.Agent/Services/_Collector/_Os.cs @@ -1,106 +1,105 @@ using Insight.Agent.Extensions; -using Insight.Agent.Messages; +using Insight.Domain.Messages.Agent; using Microsoft.Extensions.Logging; 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"); - var os = new OperationSystem(); + var os = new OperationSystem(); - // get uptime - var output = string.Empty; + // get uptime + var output = string.Empty; - // read file - using var stream = File.OpenText(@"/proc/uptime"); - output = stream.ReadToEnd(); + // read file + using var stream = File.OpenText(@"/proc/uptime"); + output = stream.ReadToEnd(); - // clean output - var clean = Regex - .Replace(output + // clean output + var clean = Regex + .Replace(output + .Trim() + .Replace("\t", " "), @"[ ]{2,}", " "); + + var elements = clean.Split(Array.Empty(), StringSplitOptions.RemoveEmptyEntries); + + // assign values + //os.Uptime = DateTime.Now - TimeSpan.FromSeconds(double.Parse(elements.ElementAt(0))); + + // request data with process + output = "hostnamectl".Bash(); + + // linebreak list conversion + var lines = new List(output + .Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) + .Select(l => + { + return Regex + .Replace(l .Trim() .Replace("\t", " "), @"[ ]{2,}", " "); + }) + .ToList(); - var elements = clean.Split(Array.Empty(), StringSplitOptions.RemoveEmptyEntries); + // assign values + os.Virtual = lines + .Any(l => l + .StartsWith("Virtualization:")) && !string.IsNullOrEmpty(lines + .Where(l => l + .StartsWith("Virtualization:")) + .First() + .Split("Virtualization:")[1] + .Trim()); - // assign values - //os.Uptime = DateTime.Now - TimeSpan.FromSeconds(double.Parse(elements.ElementAt(0))); + // OS + // request data with process + output = "hostnamectl".Bash(); - // request data with process - output = "hostnamectl".Bash(); + // linebreak list conversion + lines = new List(output + .Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) + .Select(l => + { + return Regex + .Replace(l + .Trim() + .Replace("\t", " "), @"[ ]{2,}", " "); + }) + .ToList(); - // linebreak list conversion - var lines = new List(output - .Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) - .Select(l => - { - return Regex - .Replace(l - .Trim() - .Replace("\t", " "), @"[ ]{2,}", " "); - }) - .ToList(); + // assign values + os.Name = lines + .Any(l => l + .StartsWith("Operating System:")) ? lines + .Where(l => l + .StartsWith("Operating System:")) + .First() + .Split("Operating System:")[1] + .Trim() : string.Empty; - // assign values - os.Virtual = lines - .Any(l => l - .StartsWith("Virtualization:")) && !string.IsNullOrEmpty(lines - .Where(l => l - .StartsWith("Virtualization:")) - .First() - .Split("Virtualization:")[1] - .Trim()); + os.Version = lines + .Any(l => l + .StartsWith("Kernel:")) ? lines + .Where(l => l + .StartsWith("Kernel:")) + .First() + .Split("Kernel:")[1] + .Trim() : string.Empty; - // OS - // request data with process - output = "hostnamectl".Bash(); + var architecture = lines + .Any(l => l + .StartsWith("Architecture:")) ? lines + .Where(l => l + .StartsWith("Architecture:")) + .First() + .Split("Architecture:")[1] + .Trim() : string.Empty; - // linebreak list conversion - lines = new List(output - .Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) - .Select(l => - { - return Regex - .Replace(l - .Trim() - .Replace("\t", " "), @"[ ]{2,}", " "); - }) - .ToList(); - - // assign values - os.Name = lines - .Any(l => l - .StartsWith("Operating System:")) ? lines - .Where(l => l - .StartsWith("Operating System:")) - .First() - .Split("Operating System:")[1] - .Trim() : string.Empty; - - os.Version = lines - .Any(l => l - .StartsWith("Kernel:")) ? lines - .Where(l => l - .StartsWith("Kernel:")) - .First() - .Split("Kernel:")[1] - .Trim() : string.Empty; - - var architecture = lines - .Any(l => l - .StartsWith("Architecture:")) ? lines - .Where(l => l - .StartsWith("Architecture:")) - .First() - .Split("Architecture:")[1] - .Trim() : string.Empty; - - return os; - } + return os; } } \ No newline at end of file diff --git a/src/Agent/Insight.Agent/Services/_Collector/_Session.cs b/src/Agent/Insight.Agent/Services/_Collector/_Session.cs index 3b34213..e8d1199 100644 --- a/src/Agent/Insight.Agent/Services/_Collector/_Session.cs +++ b/src/Agent/Insight.Agent/Services/_Collector/_Session.cs @@ -1,50 +1,49 @@ using Insight.Agent.Extensions; -using Insight.Agent.Messages; +using Insight.Domain.Messages.Agent; using Microsoft.Extensions.Logging; using System.Text.RegularExpressions; -namespace Insight.Agent.Services +namespace Insight.Agent.Services; + +public partial class CollectorService { - public partial class CollectorService + public List? GetSessions() { - public List? GetSessions() + Logger.LogTrace("GetSessions"); + + var sessions = new List(); + + // request data with process + var output = "w".Bash(); + + // linebreak list conversion + var lines = output.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); + + lines = lines.Select(l => { - Logger.LogTrace("GetSessions"); + return Regex.Replace(l.Trim().Replace("\t", " "), @"[ ]{2,}", " "); + }).ToList(); - var sessions = new List(); + // cleaning + lines.RemoveRange(0, 2); - // request data with process - var output = "w".Bash(); + // process list elements + foreach (var l in lines) + { + // split into elements + var elements = l.Split(Array.Empty(), StringSplitOptions.RemoveEmptyEntries); - // linebreak list conversion - var lines = output.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); - - lines = lines.Select(l => + // add user, assign values + sessions.Add(new Session { - return Regex.Replace(l.Trim().Replace("\t", " "), @"[ ]{2,}", " "); - }).ToList(); - - // cleaning - lines.RemoveRange(0, 2); - - // process list elements - foreach (var l in lines) - { - // split into elements - var elements = l.Split(Array.Empty(), StringSplitOptions.RemoveEmptyEntries); - - // add user, assign values - sessions.Add(new Session - { - User = elements.ElementAt(0), - //Id = elements.ElementAt(1), - Remote = elements.ElementAt(2), - //Login = elements.ElementAt(3), - //Idle = elements.ElementAt(4) - }); - } - - return sessions; + User = elements.ElementAt(0), + //Id = elements.ElementAt(1), + Remote = elements.ElementAt(2), + //Login = elements.ElementAt(3), + //Idle = elements.ElementAt(4) + }); } + + return sessions; } } \ No newline at end of file diff --git a/src/Api/Insight.Api/Insight.Api.csproj b/src/Api/Insight.Api/Insight.Api.csproj index 95b64f1..8deb797 100644 --- a/src/Api/Insight.Api/Insight.Api.csproj +++ b/src/Api/Insight.Api/Insight.Api.csproj @@ -4,7 +4,7 @@ net7.0 Insight api - 2023.8.23.1 + 2023.9.21.1 Insight.Api enable enable diff --git a/src/Core/Insight.Domain/Constants/Configuration.cs b/src/Core/Insight.Domain/Constants/Configuration.cs index f0643e2..812b469 100644 --- a/src/Core/Insight.Domain/Constants/Configuration.cs +++ b/src/Core/Insight.Domain/Constants/Configuration.cs @@ -1,13 +1,12 @@ using System.Net; 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 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 string DefaultConfig => Path.Combine(AppDirectory?.FullName ?? string.Empty, "config.json"); - } + public static string Hostname => Dns.GetHostEntry("localhost").HostName; + 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 string DefaultConfig => Path.Combine(AppDirectory?.FullName ?? string.Empty, "config.json"); } \ No newline at end of file diff --git a/src/Core/Insight.Domain/Enums/CategoryEnum.cs b/src/Core/Insight.Domain/Enums/CategoryEnum.cs new file mode 100644 index 0000000..739b5fd --- /dev/null +++ b/src/Core/Insight.Domain/Enums/CategoryEnum.cs @@ -0,0 +1,13 @@ +namespace Insight.Domain.Enums; + +public enum CategoryEnum +{ + Network = 1, + System = 2, + Application = 3, + Security = 4, + Monitoring = 5, + Task = 6, + Printer = 7, + RDP = 8 +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Enums/DispatchEnum.cs b/src/Core/Insight.Domain/Enums/DispatchEnum.cs new file mode 100644 index 0000000..da38f84 --- /dev/null +++ b/src/Core/Insight.Domain/Enums/DispatchEnum.cs @@ -0,0 +1,8 @@ +namespace Insight.Domain.Enums; + +public enum DispatchEnum +{ + Pending = 1, + Failure = 2, + Success = 3, +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Enums/StatusEnum.cs b/src/Core/Insight.Domain/Enums/StatusEnum.cs new file mode 100644 index 0000000..41abd57 --- /dev/null +++ b/src/Core/Insight.Domain/Enums/StatusEnum.cs @@ -0,0 +1,8 @@ +namespace Insight.Domain.Enums; + +public enum StatusEnum +{ + Information = 1, + Warning = 2, + Error = 3 +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Insight.Domain.csproj b/src/Core/Insight.Domain/Insight.Domain.csproj index 7386681..7231fd8 100644 --- a/src/Core/Insight.Domain/Insight.Domain.csproj +++ b/src/Core/Insight.Domain/Insight.Domain.csproj @@ -6,9 +6,13 @@ enable Insight.Domain Insight - 2023.7.3.0 + 2023.9.21.1 + + + + none @@ -17,4 +21,4 @@ none - + \ No newline at end of file diff --git a/src/Core/Insight.Domain/Interfaces/IAgentMessageHandler.cs b/src/Core/Insight.Domain/Interfaces/IAgentMessageHandler.cs new file mode 100644 index 0000000..b420e74 --- /dev/null +++ b/src/Core/Insight.Domain/Interfaces/IAgentMessageHandler.cs @@ -0,0 +1,8 @@ +using Insight.Domain.Messages; + +namespace Insight.Domain.Interfaces; + +public partial interface IMessageHandler +{ + ValueTask HandleAsync(TSender sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage; +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Application.cs b/src/Core/Insight.Domain/Messages/Agent/Application.cs new file mode 100644 index 0000000..45c6696 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Application.cs @@ -0,0 +1,35 @@ +using MemoryPack; +using System.Runtime.InteropServices; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Application : IMessage +{ + [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, IMessage { } \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Authentication.cs b/src/Core/Insight.Domain/Messages/Agent/Authentication.cs new file mode 100644 index 0000000..b5841ce --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Authentication.cs @@ -0,0 +1,29 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Authentication : IMessage +{ + [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 : IMessage { } \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Commands.cs b/src/Core/Insight.Domain/Messages/Agent/Commands.cs new file mode 100644 index 0000000..71853ea --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Commands.cs @@ -0,0 +1,6 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class InventoryRequest : IMessage { } \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/ConsoleQuery.cs b/src/Core/Insight.Domain/Messages/Agent/ConsoleQuery.cs new file mode 100644 index 0000000..f50d2c9 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/ConsoleQuery.cs @@ -0,0 +1,44 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class ConsoleQuery : IMessage +{ + [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 : IMessage +{ + [MemoryPackOrder(0)] + public string? Id { get; set; } + + [MemoryPackOrder(1)] + public string? HostId { get; set; } + + [MemoryPackOrder(2)] + public string? Query { get; set; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Drive.cs b/src/Core/Insight.Domain/Messages/Agent/Drive.cs new file mode 100644 index 0000000..8ac952b --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Drive.cs @@ -0,0 +1,98 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Drive : IMessage +{ + [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? Volumes { get; set; } +} + +[MemoryPackable(GenerateType.Collection)] +public partial class DriveList : List, IMessage { } + +[MemoryPackable] +public partial class Volume : IMessage +{ + [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; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Event.cs b/src/Core/Insight.Domain/Messages/Agent/Event.cs new file mode 100644 index 0000000..99bb231 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Event.cs @@ -0,0 +1,37 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Event : IMessage +{ + [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 + } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Interface.cs b/src/Core/Insight.Domain/Messages/Agent/Interface.cs new file mode 100644 index 0000000..265470d --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Interface.cs @@ -0,0 +1,190 @@ +using MemoryPack; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Interface : IMessage +{ + [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? Addresses { get; set; } + + [MemoryPackOrder(23)] + public List? Gateways { get; set; } + + [MemoryPackOrder(24)] + public List? Dns { get; set; } + + [MemoryPackOrder(25)] + public List? Dhcp { get; set; } + + [MemoryPackOrder(26)] + public List? Routes { get; set; } +} + +[MemoryPackable(GenerateType.Collection)] +public partial class InterfaceList : List, IMessage { } + +[MemoryPackable] +public partial class Unicast : IMessage +{ + [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 : IMessage +{ + [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 : IMessage +{ + [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; + } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Mainboard.cs b/src/Core/Insight.Domain/Messages/Agent/Mainboard.cs new file mode 100644 index 0000000..05d44c5 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Mainboard.cs @@ -0,0 +1,25 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Mainboard : IMessage +{ + [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; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Memory.cs b/src/Core/Insight.Domain/Messages/Agent/Memory.cs new file mode 100644 index 0000000..eb42f38 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Memory.cs @@ -0,0 +1,62 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Memory : IMessage +{ + [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, IMessage { } + +[MemoryPackable] +public partial class MemoryMetric : IMessage +{ + [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; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/OperationSystem.cs b/src/Core/Insight.Domain/Messages/Agent/OperationSystem.cs new file mode 100644 index 0000000..80bd6ff --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/OperationSystem.cs @@ -0,0 +1,26 @@ +using MemoryPack; +using System.Runtime.InteropServices; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class OperationSystem : IMessage +{ + [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; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Printer.cs b/src/Core/Insight.Domain/Messages/Agent/Printer.cs new file mode 100644 index 0000000..f77a4a7 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Printer.cs @@ -0,0 +1,25 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Printer : IMessage +{ + [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, IMessage { } \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Processor.cs b/src/Core/Insight.Domain/Messages/Agent/Processor.cs new file mode 100644 index 0000000..c11f496 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Processor.cs @@ -0,0 +1,65 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Processor : IMessage +{ + [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, IMessage { } + +[MemoryPackable] +public partial class ProcessorMetric : IMessage +{ + [MemoryPackOrder(0)] + public DateTime? Timestamp { get; set; } + + [MemoryPackOrder(1)] + public float? ProcessorUsagePercentage { get; set; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Service.cs b/src/Core/Insight.Domain/Messages/Agent/Service.cs new file mode 100644 index 0000000..eb61f63 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Service.cs @@ -0,0 +1,59 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Service : IMessage +{ + [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, IMessage { } \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Session.cs b/src/Core/Insight.Domain/Messages/Agent/Session.cs new file mode 100644 index 0000000..a9d68b8 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Session.cs @@ -0,0 +1,25 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Session : IMessage +{ + [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, IMessage { } \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Status.cs b/src/Core/Insight.Domain/Messages/Agent/Status.cs new file mode 100644 index 0000000..59264d3 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Status.cs @@ -0,0 +1,13 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Status : IMessage +{ + [MemoryPackOrder(0)] + public DateTime Timestamp { get; } = DateTime.Now; + + [MemoryPackOrder(1)] + public TimeSpan Uptime { get; set; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/StoragePool.cs b/src/Core/Insight.Domain/Messages/Agent/StoragePool.cs new file mode 100644 index 0000000..3d39ed9 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/StoragePool.cs @@ -0,0 +1,297 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class StoragePool : IMessage +{ + [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? 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? PhysicalDisks { get; set; } + + [MemoryPackOrder(14)] + public List? 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, IMessage { } + +[MemoryPackable] +public partial class PhysicalDisk : IMessage +{ + [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? States { get; set; } + + [MemoryPackOrder(8)] + public HealthState? Health { get; set; } + + [MemoryPackOrder(9)] + public List? 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 : IMessage +{ + [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? 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 + } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/SystemInfo.cs b/src/Core/Insight.Domain/Messages/Agent/SystemInfo.cs new file mode 100644 index 0000000..641202b --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/SystemInfo.cs @@ -0,0 +1,19 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class SystemInfo : IMessage +{ + [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; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Trap.cs b/src/Core/Insight.Domain/Messages/Agent/Trap.cs new file mode 100644 index 0000000..a2cd071 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Trap.cs @@ -0,0 +1,25 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Trap : IMessage +{ + [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>? Data { get; set; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Update.cs b/src/Core/Insight.Domain/Messages/Agent/Update.cs new file mode 100644 index 0000000..cf4b51f --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Update.cs @@ -0,0 +1,78 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Update : IMessage +{ + [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 : IMessage +{ + [MemoryPackOrder(0)] + public List? Installed { get; set; } + + [MemoryPackOrder(1)] + public List? Pending { get; set; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/User.cs b/src/Core/Insight.Domain/Messages/Agent/User.cs new file mode 100644 index 0000000..2ca6aed --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/User.cs @@ -0,0 +1,68 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class User : IMessage +{ + [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? Groups { get; set; } +} + +[MemoryPackable(GenerateType.Collection)] +public partial class UserList : List, IMessage { } + +[MemoryPackable] +public partial class Group : IMessage +{ + [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; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/Videocard.cs b/src/Core/Insight.Domain/Messages/Agent/Videocard.cs new file mode 100644 index 0000000..0bc8dcf --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/Videocard.cs @@ -0,0 +1,25 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class Videocard : IMessage +{ + [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, IMessage { } \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Agent/VirtualMaschine.cs b/src/Core/Insight.Domain/Messages/Agent/VirtualMaschine.cs new file mode 100644 index 0000000..e630502 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Agent/VirtualMaschine.cs @@ -0,0 +1,260 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Agent; + +[MemoryPackable] +public partial class VirtualMaschine : IMessage +{ + [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? 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, IMessage { } + +[MemoryPackable] +public partial class VirtualMaschineConfiguration : IMessage +{ + [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? 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 + } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/IMessage.cs b/src/Core/Insight.Domain/Messages/IMessage.cs new file mode 100644 index 0000000..8a7a8e5 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/IMessage.cs @@ -0,0 +1,46 @@ +using MemoryPack; + +namespace Insight.Domain.Messages; + +[MemoryPackable] +[MemoryPackUnion(0, typeof(Keepalive))] +[MemoryPackUnion(1, typeof(Agent.Authentication))] +[MemoryPackUnion(2, typeof(Agent.AuthenticationRequest))] +[MemoryPackUnion(10, typeof(Agent.InventoryRequest))] +[MemoryPackUnion(20, typeof(Agent.ConsoleQuery))] +[MemoryPackUnion(21, typeof(Agent.ConsoleQueryRequest))] +[MemoryPackUnion(100, typeof(Agent.Application))] +[MemoryPackUnion(101, typeof(Agent.ApplicationList))] +[MemoryPackUnion(102, typeof(Agent.Drive))] +[MemoryPackUnion(103, typeof(Agent.DriveList))] +[MemoryPackUnion(104, typeof(Agent.Event))] +[MemoryPackUnion(105, typeof(Agent.Interface))] +[MemoryPackUnion(106, typeof(Agent.InterfaceList))] +[MemoryPackUnion(107, typeof(Agent.Mainboard))] +[MemoryPackUnion(108, typeof(Agent.Memory))] +[MemoryPackUnion(109, typeof(Agent.MemoryList))] +[MemoryPackUnion(110, typeof(Agent.OperationSystem))] +[MemoryPackUnion(111, typeof(Agent.Printer))] +[MemoryPackUnion(112, typeof(Agent.PrinterList))] +[MemoryPackUnion(113, typeof(Agent.Processor))] +[MemoryPackUnion(114, typeof(Agent.ProcessorList))] +[MemoryPackUnion(115, typeof(Agent.Service))] +[MemoryPackUnion(116, typeof(Agent.ServiceList))] +[MemoryPackUnion(117, typeof(Agent.Session))] +[MemoryPackUnion(118, typeof(Agent.SessionList))] +[MemoryPackUnion(119, typeof(Agent.Status))] +[MemoryPackUnion(120, typeof(Agent.StoragePool))] +[MemoryPackUnion(121, typeof(Agent.StoragePoolList))] +[MemoryPackUnion(122, typeof(Agent.SystemInfo))] +[MemoryPackUnion(123, typeof(Agent.Trap))] +[MemoryPackUnion(124, typeof(Agent.Update))] +[MemoryPackUnion(125, typeof(Agent.UpdateList))] +[MemoryPackUnion(126, typeof(Agent.User))] +[MemoryPackUnion(127, typeof(Agent.UserList))] +[MemoryPackUnion(128, typeof(Agent.Videocard))] +[MemoryPackUnion(129, typeof(Agent.VideocardList))] +[MemoryPackUnion(130, typeof(Agent.VirtualMaschine))] +[MemoryPackUnion(131, typeof(Agent.VirtualMaschineList))] +[MemoryPackUnion(400, typeof(Web.ConsoleQueryProxy))] +[MemoryPackUnion(401, typeof(Web.ConsoleQueryProxyRequest))] +public partial interface IMessage { } \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Keepalive.cs b/src/Core/Insight.Domain/Messages/Keepalive.cs new file mode 100644 index 0000000..3991383 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Keepalive.cs @@ -0,0 +1,6 @@ +using MemoryPack; + +namespace Insight.Domain.Messages; + +[MemoryPackable] +public partial class Keepalive : IMessage { } \ No newline at end of file diff --git a/src/Core/Insight.Domain/Messages/Web/ConsoleProxy.cs b/src/Core/Insight.Domain/Messages/Web/ConsoleProxy.cs new file mode 100644 index 0000000..5d909d5 --- /dev/null +++ b/src/Core/Insight.Domain/Messages/Web/ConsoleProxy.cs @@ -0,0 +1,38 @@ +using MemoryPack; + +namespace Insight.Domain.Messages.Web; + +[MemoryPackable] +public partial class ConsoleQueryProxy : IMessage +{ + [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(7)] + public bool HadErrors { get; set; } +} + +[MemoryPackable] +public partial class ConsoleQueryProxyRequest : IMessage +{ + [MemoryPackOrder(0)] + public string? Id { get; set; } + + [MemoryPackOrder(1)] + public string? HostId { get; set; } + + [MemoryPackOrder(2)] + public string? Query { get; set; } +} \ No newline at end of file diff --git a/src/Core/Insight.Domain/Models/Token.cs b/src/Core/Insight.Domain/Models/Token.cs index 66d91bc..44718f3 100644 --- a/src/Core/Insight.Domain/Models/Token.cs +++ b/src/Core/Insight.Domain/Models/Token.cs @@ -1,55 +1,54 @@ using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; -namespace Insight.Domain.Models +namespace Insight.Domain.Models; + +public class TokenRequest { - public class TokenRequest + [JsonPropertyName("username"), EmailAddress, Required] + public string? Username { get; set; } + + [JsonPropertyName("password"), DataType(DataType.Password), Required] + public string? Password { get; set; } + + [JsonPropertyName("code"), DataType(DataType.Text)] + public string? Code { get; set; } +} + +public class TokenResponse +{ + [JsonPropertyName("access_token")] + public string? AccessToken { get; set; } + + [JsonPropertyName("expires_in")] + public int ExpireInSeconds { get; set; } + + [JsonPropertyName("refresh_token")] + public string? RefreshToken { get; set; } +} + +public class TokenRevokeRequest +{ + [JsonPropertyName("token"), Required] + public string? Token { get; set; } + + [JsonPropertyName("reason")] + public string? Reason { get; set; } + + public TokenRevokeRequest(string token, string? reason) { - [JsonPropertyName("username"), EmailAddress, Required] - public string Username { get; set; } - - [JsonPropertyName("password"), DataType(DataType.Password), Required] - public string Password { get; set; } - - [JsonPropertyName("code"), DataType(DataType.Text)] - public string? Code { get; set; } + Token = token; + Reason = reason; } +} - public class TokenResponse +public class TokenRefreshRequest +{ + [JsonPropertyName("token"), Required] + public string? Token { get; set; } + + public TokenRefreshRequest(string token) { - [JsonPropertyName("access_token")] - public string AccessToken { get; set; } - - [JsonPropertyName("expires_in")] - public int ExpireInSeconds { get; set; } - - [JsonPropertyName("refresh_token")] - public string RefreshToken { get; set; } - } - - public class TokenRevokeRequest - { - [JsonPropertyName("token"), Required] - public string Token { get; set; } - - [JsonPropertyName("reason")] - public string? Reason { get; set; } - - public TokenRevokeRequest(string token, string? reason) - { - Token = token; - Reason = reason; - } - } - - public class TokenRefreshRequest - { - [JsonPropertyName("token"), Required] - public string Token { get; set; } - - public TokenRefreshRequest(string token) - { - Token = token; - } + Token = token; } } \ No newline at end of file diff --git a/src/Core/Insight.Domain/Models/Update.cs b/src/Core/Insight.Domain/Models/Update.cs index 6f0fd0b..16258a3 100644 --- a/src/Core/Insight.Domain/Models/Update.cs +++ b/src/Core/Insight.Domain/Models/Update.cs @@ -1,8 +1,7 @@ -namespace Insight.Domain.Models +namespace Insight.Domain.Models; + +public class UpdateResponse { - public class UpdateResponse - { - public Version? Version { get; set; } - public Uri? Uri { get; set; } - } + public Version? Version { get; set; } + public Uri? Uri { get; set; } } \ No newline at end of file diff --git a/src/Core/Insight.Infrastructure/Insight.Infrastructure.csproj b/src/Core/Insight.Infrastructure/Insight.Infrastructure.csproj index d4cec7c..99eb1c5 100644 --- a/src/Core/Insight.Infrastructure/Insight.Infrastructure.csproj +++ b/src/Core/Insight.Infrastructure/Insight.Infrastructure.csproj @@ -4,7 +4,7 @@ net7.0 Insight.Infrastructure Insight - 2023.7.12.0 + 2023.9.21.1 true enable diff --git a/src/Server/Insight.Server/Insight.Server.csproj b/src/Server/Insight.Server/Insight.Server.csproj index 3fde5e7..5a406de 100644 --- a/src/Server/Insight.Server/Insight.Server.csproj +++ b/src/Server/Insight.Server/Insight.Server.csproj @@ -5,7 +5,7 @@ net7.0 Insight server - 2023.9.14.0 + 2023.9.21.1 Insight.Server enable enable @@ -53,9 +53,7 @@ - - diff --git a/src/Server/Insight.Server/Models/MonitorMessage.cs b/src/Server/Insight.Server/Models/MonitorMessage.cs index e3eef9a..3886d21 100644 --- a/src/Server/Insight.Server/Models/MonitorMessage.cs +++ b/src/Server/Insight.Server/Models/MonitorMessage.cs @@ -1,27 +1,26 @@ -using Insight.Agent.Enums; +using Insight.Domain.Enums; -namespace Insight.Server.Models +namespace Insight.Server.Models; + +internal class MonitorMessage { - internal class MonitorMessage - { - public DateTime? Timestamp { get; set; } - public string? Community { get; set; } - public ApplicationEnum? Application { get; set; } - public CategoryEnum? Category { get; set; } - public StatusEnum? Status { get; set; } - public string? Endpoint { get; set; } - public string? Hostname { get; set; } - public string? Subject { get; set; } - public string? Message { get; set; } + public DateTime? Timestamp { get; set; } + public string? Community { get; set; } + public ApplicationEnum? Application { get; set; } + public CategoryEnum? Category { get; set; } + public StatusEnum? Status { get; set; } + public string? Endpoint { get; set; } + public string? Hostname { get; set; } + public string? Subject { get; set; } + public string? Message { get; set; } - public enum ApplicationEnum - { - Unknown = 0, - Insight = 1, - Acronis = 2, - Veeam = 3, - QNAP = 4, - FreeNas = 5 - } + public enum ApplicationEnum + { + Unknown = 0, + Insight = 1, + Acronis = 2, + Veeam = 3, + QNAP = 4, + FreeNas = 5 } } diff --git a/src/Server/Insight.Server/Network/AgentSession.cs b/src/Server/Insight.Server/Network/AgentSession.cs index caa907a..b15549d 100644 --- a/src/Server/Insight.Server/Network/AgentSession.cs +++ b/src/Server/Insight.Server/Network/AgentSession.cs @@ -1,89 +1,89 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Server.Network.Handlers.Agent; using Microsoft.Extensions.Logging; using Vaitr.Network; -namespace Insight.Server.Network +namespace Insight.Server.Network; + +public class AgentSession : TcpSession { - public class AgentSession : TcpSession + public string? Id { get; set; } + + private readonly AgentHandler _agentHandler; + private readonly IEnumerable> _handlers; + + public AgentSession(AgentHandler agentHandler, IEnumerable> handlers, ISerializer serializer, ILogger logger) : base(serializer, logger) { - public string? Id { get; set; } + _agentHandler = agentHandler; + _handlers = handlers; + } - private readonly AgentHandler _agentHandler; - private readonly IEnumerable> _handlers; + protected override async ValueTask OnConnectedAsync(CancellationToken cancellationToken) + { + _logger.LogInformation("Agent ({ep?}) connected", RemoteEndPoint); - public AgentSession(AgentHandler agentHandler, IEnumerable> handlers, ISerializer serializer, ILogger logger) : base(serializer, logger) + var request = new AuthenticationRequest(); + + foreach (var handler in _handlers) { - _agentHandler = agentHandler; - _handlers = handlers; + await handler.HandleAsync(this, request, cancellationToken); } - protected override async ValueTask OnConnectedAsync(CancellationToken cancellationToken) + await _agentHandler.ConnectedAsync(this, default); + await _agentHandler.StatisticUpdateAsync(this, default); + + _logger.LogInformation("Agent ({ep?}) ID: {id}", RemoteEndPoint, Id); + } + + protected override async ValueTask OnDisconnectedAsync(CancellationToken cancellationToken) + { + _logger.LogInformation("Agent ({ep?}) disconnected", RemoteEndPoint); + + await _agentHandler.StatisticUpdateAsync(this, default); + await _agentHandler.DisconnectedAsync(this, default); + } + + protected override async ValueTask OnSentAsync(IPacketContext context, CancellationToken cancellationToken) + { + await base.OnSentAsync(context, cancellationToken); + + await _agentHandler.StatisticUpdateAsync(this, cancellationToken); + } + + protected override async ValueTask OnReceivedAsync(IPacketContext context, CancellationToken cancellationToken) + { + await base.OnReceivedAsync(context, cancellationToken); + + if (Id is null && context.Packet is not Authentication) return; + + await _agentHandler.StatisticUpdateAsync(this, cancellationToken); + + foreach (var handler in _handlers) { - _logger.LogInformation("Agent ({ep?}) connected", RemoteEndPoint); - - var request = new AuthenticationRequest(); - - foreach (var handler in _handlers) + try { - await handler.HandleAsync(this, request, cancellationToken); + await handler.HandleAsync(this, context.Packet, cancellationToken); } - - await _agentHandler.ConnectedAsync(this, default); - await _agentHandler.StatisticUpdateAsync(this, default); - - _logger.LogInformation("Agent ({ep?}) ID: {id}", RemoteEndPoint, Id); - } - - protected override async ValueTask OnDisconnectedAsync(CancellationToken cancellationToken) - { - _logger.LogInformation("Agent ({ep?}) disconnected", RemoteEndPoint); - - await _agentHandler.StatisticUpdateAsync(this, default); - await _agentHandler.DisconnectedAsync(this, default); - } - - protected override async ValueTask OnSentAsync(IPacketContext context, CancellationToken cancellationToken) - { - await base.OnSentAsync(context, cancellationToken); - - await _agentHandler.StatisticUpdateAsync(this, cancellationToken); - } - - protected override async ValueTask OnReceivedAsync(IPacketContext context, CancellationToken cancellationToken) - { - await base.OnReceivedAsync(context, cancellationToken); - - if (Id is null && context.Packet is not Authentication) return; - - await _agentHandler.StatisticUpdateAsync(this, cancellationToken); - - foreach (var handler in _handlers) + catch (Exception ex) { - try - { - await handler.HandleAsync(this, context.Packet, cancellationToken); - } - catch (Exception ex) - { - _logger.LogWarning("Agent ({ep?}) {ex}", RemoteEndPoint, ex.ToString()); + _logger.LogWarning("Agent ({ep?}) {ex}", RemoteEndPoint, ex.ToString()); - //await _mediator.Send(new AgentLog(new AgentLogEntity - //{ - // Category = CategoryEnum.Network.ToString(), - // Status = StatusEnum.Error.ToString(), - // Message = e.StackTrace - //}, this), cancellationToken).ConfigureAwait(false); - } + //await _mediator.Send(new AgentLog(new AgentLogEntity + //{ + // Category = CategoryEnum.Network.ToString(), + // Status = StatusEnum.Error.ToString(), + // Message = e.StackTrace + //}, this), cancellationToken).ConfigureAwait(false); } } - - protected override async ValueTask OnHeartbeatAsync(CancellationToken cancellationToken) - { - _logger.LogInformation("Agent ({ep?}) Heartbeat", RemoteEndPoint); - - await _agentHandler.StatisticUpdateAsync(this, cancellationToken); - } + } + + protected override async ValueTask OnHeartbeatAsync(CancellationToken cancellationToken) + { + _logger.LogInformation("Agent ({ep?}) Heartbeat", RemoteEndPoint); + + await _agentHandler.StatisticUpdateAsync(this, cancellationToken); } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/AgentHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/AgentHandler.cs index c7de5d8..ac0c7a6 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/AgentHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/AgentHandler.cs @@ -1,162 +1,162 @@ -using Insight.Agent.Enums; -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Enums; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using Microsoft.Extensions.Logging; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class AgentHandler : IMessageHandler { - public class AgentHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + private readonly ILogger _logger; + + public AgentHandler(IMongoDatabase database, ILogger logger) { - private readonly IMongoDatabase _database; - private readonly ILogger _logger; + _database = database; + _logger = logger; + } - public AgentHandler(IMongoDatabase database, ILogger logger) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is AuthenticationRequest authenticationRequest) { - _database = database; - _logger = logger; + await AuthenticationRequestAsync(sender, authenticationRequest, cancellationToken); } - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + if (message is Authentication authentication) { - if (message is AuthenticationRequest authenticationRequest) - { - await AuthenticationRequestAsync(sender, authenticationRequest, cancellationToken); - } - - if (message is Authentication authentication) - { - await AuthenticationAsync(sender, authentication, cancellationToken); - } - } - - private async ValueTask AuthenticationRequestAsync(AgentSession session, AuthenticationRequest message, CancellationToken cancellationToken) - { - await session.SendAsync(message, cancellationToken); - - for (int i = 0; i < 200; i++) - { - if (session.Id is not null) - { - _logger.LogInformation("Agent ({ep?}) authenticated", session.RemoteEndPoint); - return; - } - - await Task.Delay(50, cancellationToken).ConfigureAwait(false); - } - - _logger.LogError("Authentication Timeout ({ep?})", session.RemoteEndPoint); - session.Disconnect(); - } - - private async ValueTask AuthenticationAsync(AgentSession session, Authentication authentication, CancellationToken cancellationToken) - { - if (authentication is null) - { - throw new NullReferenceException($"authentication failed (empty response)"); - } - - if (authentication.Serial == default) - { - throw new InvalidDataException($"authentication failed ({nameof(authentication.Serial)})"); - } - - //if (authentication.Version == default || authentication.Version < Domain.Constants.Configuration.Version) - //{ - // throw new InvalidDataException($"authentication failed ({nameof(authentication.Version)})"); - //} - - // upsert agent - await _database.Agent().UpdateOneAsync(Builders - .Filter - .Eq(p => p.Serial, authentication.Serial.ToString()), Builders.Update - .SetOnInsert(p => p.Insert, DateTime.Now) - .SetOnInsert(p => p.Serial, authentication.Serial.ToString()) - .Set(p => p.Update, DateTime.Now) - .Set(p => p.Connected, DateTime.Now) - .Set(p => p.Version, authentication.Version) - .Set(p => p.Endpoint, session.RemoteEndPoint?.ToString()) - .Set(p => p.Hostname, authentication.Hostname), new UpdateOptions - { - IsUpsert = true - }, cancellationToken) - .ConfigureAwait(false); - - // get agent - var agentEntity = await _database.Agent() - .Find(Builders - .Filter - .Eq(p => p.Serial, authentication.Serial.ToString())) - .FirstOrDefaultAsync(cancellationToken) - .ConfigureAwait(false); - - // set session id - session.Id = agentEntity.Id; - } - - public async ValueTask ConnectedAsync(AgentSession session, CancellationToken cancellationToken) - { - if (session.Id is null) return; - - // insert connect log - await _database.AgentLog() - .InsertOneAsync(new AgentLogEntity - { - Insert = DateTime.Now, - Agent = session.Id, - Category = CategoryEnum.Network.ToString(), - Status = StatusEnum.Information.ToString(), - Message = $"Connected ({session.RemoteEndPoint})", - Timestamp = DateTime.Now - }, cancellationToken: cancellationToken) - .ConfigureAwait(false); - } - - public async ValueTask DisconnectedAsync(AgentSession session, CancellationToken cancellationToken) - { - if (session.Id is null) return; - - // insert disconnect log - await _database.AgentLog() - .InsertOneAsync(new AgentLogEntity - { - Insert = DateTime.Now, - Agent = session.Id, - Category = CategoryEnum.Network.ToString(), - Status = StatusEnum.Information.ToString(), - Message = $"Disconnected ({session.RemoteEndPoint})", - Timestamp = DateTime.Now - }, cancellationToken: cancellationToken) - .ConfigureAwait(false); - } - - public async ValueTask StatisticUpdateAsync(AgentSession session, CancellationToken cancellationToken) - { - if (session.Id is null) return; - - // update agents stats - await _database.Agent().UpdateOneAsync(Builders - .Filter - .Eq(p => p.Id, session.Id), Builders - .Update - .Set(p => p.Update, DateTime.Now) - .Set(p => p.Activity, session.Activity) - .Set(p => p.SentBytes, session.SentBytes) - .Set(p => p.ReceivedBytes, session.ReceivedBytes) - .Set(p => p.SentPackets, session.SentPackets) - .Set(p => p.ReceivedPackets, session.ReceivedPackets), null, cancellationToken) - .ConfigureAwait(false); - } - - public async ValueTask LogAsync(AgentSession session, AgentLogEntity log, CancellationToken cancellationToken) - { - if (session.Id is null) return; - - await _database.AgentLog() - .InsertOneAsync(log, cancellationToken: cancellationToken) - .ConfigureAwait(false); + await AuthenticationAsync(sender, authentication, cancellationToken); } } + + private async ValueTask AuthenticationRequestAsync(AgentSession session, AuthenticationRequest message, CancellationToken cancellationToken) + { + await session.SendAsync(message, cancellationToken); + + for (int i = 0; i < 200; i++) + { + if (session.Id is not null) + { + _logger.LogInformation("Agent ({ep?}) authenticated", session.RemoteEndPoint); + return; + } + + await Task.Delay(50, cancellationToken).ConfigureAwait(false); + } + + _logger.LogError("Authentication Timeout ({ep?})", session.RemoteEndPoint); + session.Disconnect(); + } + + private async ValueTask AuthenticationAsync(AgentSession session, Authentication authentication, CancellationToken cancellationToken) + { + if (authentication is null) + { + throw new NullReferenceException($"authentication failed (empty response)"); + } + + if (authentication.Serial == default) + { + throw new InvalidDataException($"authentication failed ({nameof(authentication.Serial)})"); + } + + //if (authentication.Version == default || authentication.Version < Domain.Constants.Configuration.Version) + //{ + // throw new InvalidDataException($"authentication failed ({nameof(authentication.Version)})"); + //} + + // upsert agent + await _database.Agent().UpdateOneAsync(Builders + .Filter + .Eq(p => p.Serial, authentication.Serial.ToString()), Builders.Update + .SetOnInsert(p => p.Insert, DateTime.Now) + .SetOnInsert(p => p.Serial, authentication.Serial.ToString()) + .Set(p => p.Update, DateTime.Now) + .Set(p => p.Connected, DateTime.Now) + .Set(p => p.Version, authentication.Version) + .Set(p => p.Endpoint, session.RemoteEndPoint?.ToString()) + .Set(p => p.Hostname, authentication.Hostname), new UpdateOptions + { + IsUpsert = true + }, cancellationToken) + .ConfigureAwait(false); + + // get agent + var agentEntity = await _database.Agent() + .Find(Builders + .Filter + .Eq(p => p.Serial, authentication.Serial.ToString())) + .FirstOrDefaultAsync(cancellationToken) + .ConfigureAwait(false); + + // set session id + session.Id = agentEntity.Id; + } + + public async ValueTask ConnectedAsync(AgentSession session, CancellationToken cancellationToken) + { + if (session.Id is null) return; + + // insert connect log + await _database.AgentLog() + .InsertOneAsync(new AgentLogEntity + { + Insert = DateTime.Now, + Agent = session.Id, + Category = CategoryEnum.Network.ToString(), + Status = StatusEnum.Information.ToString(), + Message = $"Connected ({session.RemoteEndPoint})", + Timestamp = DateTime.Now + }, cancellationToken: cancellationToken) + .ConfigureAwait(false); + } + + public async ValueTask DisconnectedAsync(AgentSession session, CancellationToken cancellationToken) + { + if (session.Id is null) return; + + // insert disconnect log + await _database.AgentLog() + .InsertOneAsync(new AgentLogEntity + { + Insert = DateTime.Now, + Agent = session.Id, + Category = CategoryEnum.Network.ToString(), + Status = StatusEnum.Information.ToString(), + Message = $"Disconnected ({session.RemoteEndPoint})", + Timestamp = DateTime.Now + }, cancellationToken: cancellationToken) + .ConfigureAwait(false); + } + + public async ValueTask StatisticUpdateAsync(AgentSession session, CancellationToken cancellationToken) + { + if (session.Id is null) return; + + // update agents stats + await _database.Agent().UpdateOneAsync(Builders + .Filter + .Eq(p => p.Id, session.Id), Builders + .Update + .Set(p => p.Update, DateTime.Now) + .Set(p => p.Activity, session.Activity) + .Set(p => p.SentBytes, session.SentBytes) + .Set(p => p.ReceivedBytes, session.ReceivedBytes) + .Set(p => p.SentPackets, session.SentPackets) + .Set(p => p.ReceivedPackets, session.ReceivedPackets), null, cancellationToken) + .ConfigureAwait(false); + } + + public async ValueTask LogAsync(AgentSession session, AgentLogEntity log, CancellationToken cancellationToken) + { + if (session.Id is null) return; + + await _database.AgentLog() + .InsertOneAsync(log, cancellationToken: cancellationToken) + .ConfigureAwait(false); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/ConsoleHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/ConsoleHandler.cs index 23eb2d3..33e7fb0 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/ConsoleHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/ConsoleHandler.cs @@ -1,50 +1,50 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; -using Insight.Web.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; +using Insight.Domain.Messages.Web; using Microsoft.Extensions.Logging; using MongoDB.Driver; using Vaitr.Network; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class ConsoleHandler : IMessageHandler { - public class ConsoleHandler : IAgentMessageHandler + private readonly ISessionPool _webPool; + private readonly IMongoDatabase _database; + private readonly ILogger _logger; + + public ConsoleHandler( + ISessionPool webPool, + IMongoDatabase database, + ILogger logger) { - private readonly ISessionPool _webPool; - private readonly IMongoDatabase _database; - private readonly ILogger _logger; + _webPool = webPool; + _database = database; + _logger = logger; + } - public ConsoleHandler( - ISessionPool webPool, - IMongoDatabase database, - ILogger logger) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is ConsoleQuery consoleQuery) { - _webPool = webPool; - _database = database; - _logger = logger; - } - - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is ConsoleQuery consoleQuery) - { - await OnConsoleQueryAsync(sender, consoleQuery, cancellationToken); - } - } - - private async ValueTask OnConsoleQueryAsync(AgentSession session, ConsoleQuery query, CancellationToken cancellationToken) - { - // check if web online - if (_webPool.FirstOrDefault().Value is not WebSession web) return; - - await web.SendAsync(new ConsoleQueryProxy - { - Id = query.Id, - HostId = query.HostId, - Query = query.Query, - Data = query.Data, - Errors = query.Errors, - HadErrors = query.HadErrors - }, cancellationToken); + await OnConsoleQueryAsync(sender, consoleQuery, cancellationToken); } } + + private async ValueTask OnConsoleQueryAsync(AgentSession session, ConsoleQuery query, CancellationToken cancellationToken) + { + // check if web online + if (_webPool.FirstOrDefault().Value is not WebSession web) return; + + await web.SendAsync(new ConsoleQueryProxy + { + Id = query.Id, + HostId = query.HostId, + Query = query.Query, + Data = query.Data, + Errors = query.Errors, + HadErrors = query.HadErrors + }, cancellationToken); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/DriveHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/DriveHandler.cs index ec5652c..51435e1 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/DriveHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/DriveHandler.cs @@ -1,145 +1,145 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class DriveHandler : IMessageHandler { - public class DriveHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public DriveHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public DriveHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is DriveList drives) { - _database = database; + await OnDrivesAsync(sender, drives, cancellationToken); } + } - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + private async ValueTask OnDrivesAsync(AgentSession session, List drives, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + var driveBulk = new List>(); + + if (drives is not null && drives.Any()) { - if (message is DriveList drives) + foreach (var drive in drives) { - await OnDrivesAsync(sender, drives, cancellationToken); - } - } - - private async ValueTask OnDrivesAsync(AgentSession session, List drives, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - var driveBulk = new List>(); - - if (drives is not null && drives.Any()) - { - foreach (var drive in drives) - { - var driveFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Index, drive.Index) - }); - - var driveUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Index, drive.Index) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - .Set(p => p.Company, drive.Manufacturer) - .Set(p => p.Name, drive.Name) - .Set(p => p.Size, drive.Size) - .Set(p => p.Type, drive.InterfaceType) - .Set(p => p.Serial, drive.SerialNumber) - .Set(p => p.Firmware, drive.FirmwareRevision) - .Set(p => p.Status, drive.Status) - .Set(p => p.Pnp, drive.PNPDeviceID); - - driveBulk.Add(new UpdateOneModel(driveFilter, driveUpdate) - { - IsUpsert = true - }); - } - } - - driveBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + var driveFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); + Builders.Filter.Eq(x => x.Index, drive.Index) + }); - var driveResult = await _database.HostDrive().BulkWriteAsync(driveBulk, cancellationToken: cancellationToken); + var driveUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Index, drive.Index) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + .Set(p => p.Company, drive.Manufacturer) + .Set(p => p.Name, drive.Name) + .Set(p => p.Size, drive.Size) + .Set(p => p.Type, drive.InterfaceType) + .Set(p => p.Serial, drive.SerialNumber) + .Set(p => p.Firmware, drive.FirmwareRevision) + .Set(p => p.Status, drive.Status) + .Set(p => p.Pnp, drive.PNPDeviceID); - // volumes - - var volumeBulk = new List>(); - - if (drives is not null && drives.Any()) - { - foreach (var drive in drives) + driveBulk.Add(new UpdateOneModel(driveFilter, driveUpdate) { - var driveId = await _database.HostDrive() - .Find(p => p.Host == hostEntity.Id && p.Index == drive.Index) - .Project(p => p.Id) - .FirstOrDefaultAsync(); + IsUpsert = true + }); + } + } - if (drive.Volumes is not null && drive.Volumes.Any()) + driveBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var driveResult = await _database.HostDrive().BulkWriteAsync(driveBulk, cancellationToken: cancellationToken); + + // volumes + + var volumeBulk = new List>(); + + if (drives is not null && drives.Any()) + { + foreach (var drive in drives) + { + var driveId = await _database.HostDrive() + .Find(p => p.Host == hostEntity.Id && p.Index == drive.Index) + .Project(p => p.Id) + .FirstOrDefaultAsync(); + + if (drive.Volumes is not null && drive.Volumes.Any()) + { + foreach (var volume in drive.Volumes) { - foreach (var volume in drive.Volumes) - { - var volumeFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Drive, driveId), - Builders.Filter.Eq(x => x.Index, volume.Index) - }); - - var volumeUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Drive, driveId) - .SetOnInsert(p => p.Index, volume.Index) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - .Set(p => p.Name, volume.Name) - .Set(p => p.Label, volume.Id) - .Set(p => p.Serial, volume.SerialNumber) - .Set(p => p.Size, volume.Size) - .Set(p => p.FreeSpace, volume.FreeSpace) - .Set(p => p.Type, volume.Type) - .Set(p => p.FileSystem, volume.FileSystem) - .Set(p => p.Compressed, volume.Compressed) - .Set(p => p.Bootable, volume.Bootable) - .Set(p => p.Primary, volume.PrimaryPartition) - .Set(p => p.Boot, volume.Bootable) - .Set(p => p.BlockSize, volume.BlockSize) - .Set(p => p.Blocks, volume.NumberOfBlocks) - .Set(p => p.StartingOffset, volume.StartingOffset) - .Set(p => p.Provider, volume.ProviderName); - - volumeBulk.Add(new UpdateOneModel(volumeFilter, volumeUpdate) + var volumeFilter = Builders.Filter.And(new List> { - IsUpsert = true + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Eq(x => x.Drive, driveId), + Builders.Filter.Eq(x => x.Index, volume.Index) }); - } + + var volumeUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Drive, driveId) + .SetOnInsert(p => p.Index, volume.Index) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + .Set(p => p.Name, volume.Name) + .Set(p => p.Label, volume.Id) + .Set(p => p.Serial, volume.SerialNumber) + .Set(p => p.Size, volume.Size) + .Set(p => p.FreeSpace, volume.FreeSpace) + .Set(p => p.Type, volume.Type) + .Set(p => p.FileSystem, volume.FileSystem) + .Set(p => p.Compressed, volume.Compressed) + .Set(p => p.Bootable, volume.Bootable) + .Set(p => p.Primary, volume.PrimaryPartition) + .Set(p => p.Boot, volume.Bootable) + .Set(p => p.BlockSize, volume.BlockSize) + .Set(p => p.Blocks, volume.NumberOfBlocks) + .Set(p => p.StartingOffset, volume.StartingOffset) + .Set(p => p.Provider, volume.ProviderName); + + volumeBulk.Add(new UpdateOneModel(volumeFilter, volumeUpdate) + { + IsUpsert = true + }); } } } - - volumeBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var volumeResult = await _database.HostVolume().BulkWriteAsync(volumeBulk, cancellationToken: cancellationToken); } + + volumeBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var volumeResult = await _database.HostVolume().BulkWriteAsync(volumeBulk, cancellationToken: cancellationToken); } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/EventHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/EventHandler.cs index 1bd5c22..78077bc 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/EventHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/EventHandler.cs @@ -1,266 +1,266 @@ -using Insight.Agent.Enums; -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Enums; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using Microsoft.Extensions.Logging; using MongoDB.Driver; -using static Insight.Agent.Messages.Event; +using static Insight.Domain.Messages.Agent.Event; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class EventHandler : IMessageHandler { - public class EventHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + private readonly ILogger _logger; + + public EventHandler(IMongoDatabase database, ILogger logger) { - private readonly IMongoDatabase _database; - private readonly ILogger _logger; + _database = database; + _logger = logger; + } - public EventHandler(IMongoDatabase database, ILogger logger) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is Event @event) { - _database = database; - _logger = logger; - } - - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is Event @event) - { - await OnEventAsync(sender, @event, cancellationToken); - } - } - - private async ValueTask OnEventAsync(AgentSession session, Event @event, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - if (FilterEventId(@event)) return; - - var hostLog = await InsertHostLogAsync(hostEntity, @event, cancellationToken); - - if (hostLog is null || FilterMonitoringHostLog(hostLog)) return; - - await _database.HostLogMonitoring() - .InsertOneAsync(new HostLogMonitoringEntity - { - Host = hostEntity.Id, - Insert = hostLog.Insert, - Timestamp = hostLog.Timestamp, - Category = hostLog.Category, - Status = hostLog.Status, - Message = hostLog.Message, - Dispatch = DispatchEnum.Pending.ToString() - }, cancellationToken: cancellationToken); - } - - private async ValueTask InsertAgentLogAsync(AgentSession session, Event @event, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent() - .Aggregate() - .Match(Builders.Filter.Eq(p => p.Id, session.Id)) - .Lookup(_database.Host(), p => p.Serial, p => p.Agent, p => p.Hosts) - .FirstOrDefaultAsync(cancellationToken); - - if (agentEntity is null) return null; - - StatusEnum? status = @event.Status switch - { - StatusType.Information => StatusEnum.Information, - StatusType.Warning => StatusEnum.Warning, - StatusType.Error => StatusEnum.Error, - _ => null - }; - - CategoryEnum? category = @event.Category.ToLower() switch - { - "network" => CategoryEnum.Network, - "application" => CategoryEnum.Application, - "security" => CategoryEnum.Security, - "system" => CategoryEnum.System, - _ => null - }; - - var date = DateTime.Now; - - var log = new AgentLogEntity - { - Insert = date, - Agent = agentEntity.Id, - Timestamp = @event.Timestamp, - EventId = @event.EventId.ToString(), - Source = @event.Source, - Status = status.ToString(), - Category = category.ToString(), - Message = @event.Message - }; - - await _database.AgentLog().InsertOneAsync(log, cancellationToken: cancellationToken); - return log; - } - - private async ValueTask InsertHostLogAsync(HostEntity hostEntity, Event @event, CancellationToken cancellationToken) - { - StatusEnum? status = @event.Status switch - { - StatusType.Information => StatusEnum.Information, - StatusType.Warning => StatusEnum.Warning, - StatusType.Error => StatusEnum.Error, - StatusType.Critical => StatusEnum.Error, - StatusType.Unknown => null, - _ => null - }; - - CategoryEnum? category = null; - switch (@event.Category) - { - case var _ when @event.Category.Contains("network", StringComparison.InvariantCultureIgnoreCase): - category = CategoryEnum.Network; - break; - - case var _ when @event.Category.Contains("application", StringComparison.InvariantCultureIgnoreCase): - category = CategoryEnum.Application; - break; - - case var _ when @event.Category.Contains("security", StringComparison.InvariantCultureIgnoreCase): - category = CategoryEnum.Security; - break; - - case var _ when @event.Category.Contains("system", StringComparison.InvariantCultureIgnoreCase): - category = CategoryEnum.System; - break; - - case var _ when @event.Category.Contains("printservice", StringComparison.InvariantCultureIgnoreCase): - category = CategoryEnum.Printer; - break; - - case var _ when @event.Category.Contains("taskscheduler", StringComparison.InvariantCultureIgnoreCase): - category = CategoryEnum.Task; - break; - - case var _ when @event.Category.Contains("terminalservices", StringComparison.InvariantCultureIgnoreCase): - category = CategoryEnum.RDP; - break; - - case var _ when @event.Category.Contains("smbclient", StringComparison.InvariantCultureIgnoreCase): - category = CategoryEnum.Network; - break; - - case var _ when @event.Category.Contains("smbserver", StringComparison.InvariantCultureIgnoreCase): - category = CategoryEnum.Network; - break; - - case var _ when @event.Category.Contains("storagespaces", StringComparison.InvariantCultureIgnoreCase): - category = CategoryEnum.System; - break; - - case var _ when @event.Category.Contains("diagnostics", StringComparison.InvariantCultureIgnoreCase): - category = CategoryEnum.System; - break; - - default: - break; - } - - var date = DateTime.Now; - - var log = new HostLogEntity - { - Insert = date, - Host = hostEntity.Id, - Timestamp = @event.Timestamp, - EventId = @event.EventId.ToString(), - Status = status.ToString(), - Source = @event.Source, - Category = category?.ToString(), - Message = @event.Message - }; - - await _database.HostLog().InsertOneAsync(log, cancellationToken: cancellationToken); - return log; - } - - private bool FilterEventId(Event @event) - { - var filter = new List - { - 0, - 3, - 4, - 16, - 37, - 900, - 902, - 903, - 1001, - 1003, - 1008, - 1023, - 1066, - 4624, - 4625, - 4634, - 4648, - 4672, - 4776, - 4798, - 4799, - 5058, - 5059, - 5061, - 5379, - 5612, - 5781, - //7036, - 8014, - 8016, - 8019, - 8194, - 8224, - 9009, - 9027, - 10001, - 10016, - 16384, - 16394, - 36874, - 36888, - }; - - if (filter.Any(p => p == @event.EventId)) return true; - return false; - } - - private bool FilterMonitoringHostLog(HostLogEntity hostLog) - { - //_logger.LogDebug($"try filter event: {hostLog.Category}.{hostLog.Source}.{hostLog.Status}"); - - if (Enum.TryParse(hostLog.Status, out StatusType status) is false) return true; - - if (hostLog.Category == CategoryEnum.System.ToString()) - { - if (hostLog.Source == "Service Control Manager" && status < StatusType.Warning) return true; - } - - if (hostLog.Category == CategoryEnum.Task.ToString()) - { - if (status < StatusType.Error) return true; - } - - // skip rdp infos - if (hostLog.Category == CategoryEnum.RDP.ToString()) - { - if (hostLog.EventId == "261") return true; - } - - // skip smbclient (veeam errors) - if (hostLog.Category == CategoryEnum.Security.ToString()) - { - if (hostLog.Source == "Microsoft-Windows-SMBClient") return true; - } - - return false; + await OnEventAsync(sender, @event, cancellationToken); } } + + private async ValueTask OnEventAsync(AgentSession session, Event @event, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + if (FilterEventId(@event)) return; + + var hostLog = await InsertHostLogAsync(hostEntity, @event, cancellationToken); + + if (hostLog is null || FilterMonitoringHostLog(hostLog)) return; + + await _database.HostLogMonitoring() + .InsertOneAsync(new HostLogMonitoringEntity + { + Host = hostEntity.Id, + Insert = hostLog.Insert, + Timestamp = hostLog.Timestamp, + Category = hostLog.Category, + Status = hostLog.Status, + Message = hostLog.Message, + Dispatch = DispatchEnum.Pending.ToString() + }, cancellationToken: cancellationToken); + } + + private async ValueTask InsertAgentLogAsync(AgentSession session, Event @event, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent() + .Aggregate() + .Match(Builders.Filter.Eq(p => p.Id, session.Id)) + .Lookup(_database.Host(), p => p.Serial, p => p.Agent, p => p.Hosts) + .FirstOrDefaultAsync(cancellationToken); + + if (agentEntity is null) return null; + + StatusEnum? status = @event.Status switch + { + StatusType.Information => StatusEnum.Information, + StatusType.Warning => StatusEnum.Warning, + StatusType.Error => StatusEnum.Error, + _ => null + }; + + CategoryEnum? category = @event.Category.ToLower() switch + { + "network" => CategoryEnum.Network, + "application" => CategoryEnum.Application, + "security" => CategoryEnum.Security, + "system" => CategoryEnum.System, + _ => null + }; + + var date = DateTime.Now; + + var log = new AgentLogEntity + { + Insert = date, + Agent = agentEntity.Id, + Timestamp = @event.Timestamp, + EventId = @event.EventId.ToString(), + Source = @event.Source, + Status = status.ToString(), + Category = category.ToString(), + Message = @event.Message + }; + + await _database.AgentLog().InsertOneAsync(log, cancellationToken: cancellationToken); + return log; + } + + private async ValueTask InsertHostLogAsync(HostEntity hostEntity, Event @event, CancellationToken cancellationToken) + { + StatusEnum? status = @event.Status switch + { + StatusType.Information => StatusEnum.Information, + StatusType.Warning => StatusEnum.Warning, + StatusType.Error => StatusEnum.Error, + StatusType.Critical => StatusEnum.Error, + StatusType.Unknown => null, + _ => null + }; + + CategoryEnum? category = null; + switch (@event.Category) + { + case var _ when @event.Category.Contains("network", StringComparison.InvariantCultureIgnoreCase): + category = CategoryEnum.Network; + break; + + case var _ when @event.Category.Contains("application", StringComparison.InvariantCultureIgnoreCase): + category = CategoryEnum.Application; + break; + + case var _ when @event.Category.Contains("security", StringComparison.InvariantCultureIgnoreCase): + category = CategoryEnum.Security; + break; + + case var _ when @event.Category.Contains("system", StringComparison.InvariantCultureIgnoreCase): + category = CategoryEnum.System; + break; + + case var _ when @event.Category.Contains("printservice", StringComparison.InvariantCultureIgnoreCase): + category = CategoryEnum.Printer; + break; + + case var _ when @event.Category.Contains("taskscheduler", StringComparison.InvariantCultureIgnoreCase): + category = CategoryEnum.Task; + break; + + case var _ when @event.Category.Contains("terminalservices", StringComparison.InvariantCultureIgnoreCase): + category = CategoryEnum.RDP; + break; + + case var _ when @event.Category.Contains("smbclient", StringComparison.InvariantCultureIgnoreCase): + category = CategoryEnum.Network; + break; + + case var _ when @event.Category.Contains("smbserver", StringComparison.InvariantCultureIgnoreCase): + category = CategoryEnum.Network; + break; + + case var _ when @event.Category.Contains("storagespaces", StringComparison.InvariantCultureIgnoreCase): + category = CategoryEnum.System; + break; + + case var _ when @event.Category.Contains("diagnostics", StringComparison.InvariantCultureIgnoreCase): + category = CategoryEnum.System; + break; + + default: + break; + } + + var date = DateTime.Now; + + var log = new HostLogEntity + { + Insert = date, + Host = hostEntity.Id, + Timestamp = @event.Timestamp, + EventId = @event.EventId.ToString(), + Status = status.ToString(), + Source = @event.Source, + Category = category?.ToString(), + Message = @event.Message + }; + + await _database.HostLog().InsertOneAsync(log, cancellationToken: cancellationToken); + return log; + } + + private bool FilterEventId(Event @event) + { + var filter = new List + { + 0, + 3, + 4, + 16, + 37, + 900, + 902, + 903, + 1001, + 1003, + 1008, + 1023, + 1066, + 4624, + 4625, + 4634, + 4648, + 4672, + 4776, + 4798, + 4799, + 5058, + 5059, + 5061, + 5379, + 5612, + 5781, + //7036, + 8014, + 8016, + 8019, + 8194, + 8224, + 9009, + 9027, + 10001, + 10016, + 16384, + 16394, + 36874, + 36888, + }; + + if (filter.Any(p => p == @event.EventId)) return true; + return false; + } + + private bool FilterMonitoringHostLog(HostLogEntity hostLog) + { + //_logger.LogDebug($"try filter event: {hostLog.Category}.{hostLog.Source}.{hostLog.Status}"); + + if (Enum.TryParse(hostLog.Status, out StatusType status) is false) return true; + + if (hostLog.Category == CategoryEnum.System.ToString()) + { + if (hostLog.Source == "Service Control Manager" && status < StatusType.Warning) return true; + } + + if (hostLog.Category == CategoryEnum.Task.ToString()) + { + if (status < StatusType.Error) return true; + } + + // skip rdp infos + if (hostLog.Category == CategoryEnum.RDP.ToString()) + { + if (hostLog.EventId == "261") return true; + } + + // skip smbclient (veeam errors) + if (hostLog.Category == CategoryEnum.Security.ToString()) + { + if (hostLog.Source == "Microsoft-Windows-SMBClient") return true; + } + + return false; + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/InterfaceHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/InterfaceHandler.cs index 7cfc212..b9b5e5d 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/InterfaceHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/InterfaceHandler.cs @@ -1,299 +1,299 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class InterfaceHandler : IMessageHandler { - public class InterfaceHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public InterfaceHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public InterfaceHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is InterfaceList interfaces) { - _database = database; + await OnInterfacesAsync(sender, interfaces, cancellationToken); } + } - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + private async ValueTask OnInterfacesAsync(AgentSession session, List interfaces, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + // interfaces + + if (interfaces is not null && interfaces.Any()) { - if (message is InterfaceList interfaces) + var interfaceBulk = new List>(); + + foreach (var @interface in interfaces) { - await OnInterfacesAsync(sender, interfaces, cancellationToken); - } - } - - private async ValueTask OnInterfacesAsync(AgentSession session, List interfaces, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - // interfaces - - if (interfaces is not null && interfaces.Any()) - { - var interfaceBulk = new List>(); - - foreach (var @interface in interfaces) - { - var interfaceFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Index, @interface.Index) - }); - - var interfaceUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Index, @interface.Index) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - - .Set(p => p.Mac, @interface?.Mac) - .Set(p => p.Name, @interface?.Name) - .Set(p => p.Description, @interface?.Description) - .Set(p => p.Physical, @interface?.Physical) - .Set(p => p.Status, @interface?.Status?.ToString()) - .Set(p => p.Suffix, @interface?.Suffix) - .Set(p => p.Speed, @interface?.Speed) - .Set(p => p.Ipv4Mtu, @interface?.Ipv4Mtu) - .Set(p => p.Ipv4Dhcp, @interface?.Ipv4Dhcp) - - .Set(p => p.Ipv4Forwarding, @interface?.Ipv4Forwarding) - .Set(p => p.Ipv6Mtu, @interface?.Ipv6Mtu) - .Set(p => p.Sent, @interface?.Sent) - .Set(p => p.Received, @interface?.Received) - .Set(p => p.IncomingPacketsDiscarded, @interface?.IncomingPacketsDiscarded) - .Set(p => p.IncomingPacketsWithErrors, @interface?.IncomingPacketsWithErrors) - .Set(p => p.IncomingUnknownProtocolPackets, @interface?.IncomingUnknownProtocolPackets) - .Set(p => p.OutgoingPacketsDiscarded, @interface?.OutgoingPacketsDiscarded) - .Set(p => p.OutgoingPacketsWithErrors, @interface?.OutgoingPacketsWithErrors); - - interfaceBulk.Add(new UpdateOneModel(interfaceFilter, interfaceUpdate) - { - IsUpsert = true - }); - } - - interfaceBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + var interfaceFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); + Builders.Filter.Eq(x => x.Index, @interface.Index) + }); - var interfaceResult = await _database.HostInterface().BulkWriteAsync(interfaceBulk, cancellationToken: cancellationToken); + var interfaceUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Index, @interface.Index) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + + .Set(p => p.Mac, @interface?.Mac) + .Set(p => p.Name, @interface?.Name) + .Set(p => p.Description, @interface?.Description) + .Set(p => p.Physical, @interface?.Physical) + .Set(p => p.Status, @interface?.Status?.ToString()) + .Set(p => p.Suffix, @interface?.Suffix) + .Set(p => p.Speed, @interface?.Speed) + .Set(p => p.Ipv4Mtu, @interface?.Ipv4Mtu) + .Set(p => p.Ipv4Dhcp, @interface?.Ipv4Dhcp) + + .Set(p => p.Ipv4Forwarding, @interface?.Ipv4Forwarding) + .Set(p => p.Ipv6Mtu, @interface?.Ipv6Mtu) + .Set(p => p.Sent, @interface?.Sent) + .Set(p => p.Received, @interface?.Received) + .Set(p => p.IncomingPacketsDiscarded, @interface?.IncomingPacketsDiscarded) + .Set(p => p.IncomingPacketsWithErrors, @interface?.IncomingPacketsWithErrors) + .Set(p => p.IncomingUnknownProtocolPackets, @interface?.IncomingUnknownProtocolPackets) + .Set(p => p.OutgoingPacketsDiscarded, @interface?.OutgoingPacketsDiscarded) + .Set(p => p.OutgoingPacketsWithErrors, @interface?.OutgoingPacketsWithErrors); + + interfaceBulk.Add(new UpdateOneModel(interfaceFilter, interfaceUpdate) + { + IsUpsert = true + }); } - // addresses - - if (interfaces is not null && interfaces.Any()) - { - var addressBulk = new List>(); - - foreach (var @interface in interfaces) + interfaceBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> { - var interfaceId = await _database.HostInterface() - .Find(p => p.Host == hostEntity.Id && p.Index == @interface.Index) - .Project(p => p.Id) - .FirstOrDefaultAsync(); + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); - if (@interface.Addresses is not null && @interface.Addresses.Any()) + var interfaceResult = await _database.HostInterface().BulkWriteAsync(interfaceBulk, cancellationToken: cancellationToken); + } + + // addresses + + if (interfaces is not null && interfaces.Any()) + { + var addressBulk = new List>(); + + foreach (var @interface in interfaces) + { + var interfaceId = await _database.HostInterface() + .Find(p => p.Host == hostEntity.Id && p.Index == @interface.Index) + .Project(p => p.Id) + .FirstOrDefaultAsync(); + + if (@interface.Addresses is not null && @interface.Addresses.Any()) + { + foreach (var address in @interface.Addresses) { - foreach (var address in @interface.Addresses) - { - var addressFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Interface, interfaceId), - Builders.Filter.Eq(x => x.Address, address?.IpAddress?.Address), - Builders.Filter.Eq(x => x.Mask, address?.Ipv4Mask?.Address) - }); - - var addressUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Interface, interfaceId) - .SetOnInsert(p => p.Address, address?.IpAddress?.Address) - .SetOnInsert(p => p.Mask, address?.Ipv4Mask?.Address) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch); - - addressBulk.Add(new UpdateOneModel(addressFilter, addressUpdate) - { - IsUpsert = true - }); - } - } - } - - addressBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + var addressFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var addressResult = await _database.HostInterfaceAddress().BulkWriteAsync(addressBulk, cancellationToken: cancellationToken); - } - - // gateways - - if (interfaces is not null && interfaces.Any()) - { - var gatewayBulk = new List>(); - - foreach (var @interface in interfaces) - { - var interfaceId = await _database.HostInterface() - .Find(p => p.Host == hostEntity.Id && p.Index == @interface.Index) - .Project(p => p.Id) - .FirstOrDefaultAsync(); - - if (@interface.Gateways is not null && @interface.Gateways.Any()) - { - foreach (var gateway in @interface.Gateways) - { - var gatewayFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Interface, interfaceId), - Builders.Filter.Eq(x => x.Address, gateway?.Address) - }); - - var gatewayUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Interface, interfaceId) - .SetOnInsert(p => p.Address, gateway?.Address) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch); - - gatewayBulk.Add(new UpdateOneModel(gatewayFilter, gatewayUpdate) - { - IsUpsert = true + Builders.Filter.Eq(x => x.Interface, interfaceId), + Builders.Filter.Eq(x => x.Address, address?.IpAddress?.Address), + Builders.Filter.Eq(x => x.Mask, address?.Ipv4Mask?.Address) }); - } + + var addressUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Interface, interfaceId) + .SetOnInsert(p => p.Address, address?.IpAddress?.Address) + .SetOnInsert(p => p.Mask, address?.Ipv4Mask?.Address) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch); + + addressBulk.Add(new UpdateOneModel(addressFilter, addressUpdate) + { + IsUpsert = true + }); } } + } - gatewayBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + addressBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var addressResult = await _database.HostInterfaceAddress().BulkWriteAsync(addressBulk, cancellationToken: cancellationToken); + } + + // gateways + + if (interfaces is not null && interfaces.Any()) + { + var gatewayBulk = new List>(); + + foreach (var @interface in interfaces) + { + var interfaceId = await _database.HostInterface() + .Find(p => p.Host == hostEntity.Id && p.Index == @interface.Index) + .Project(p => p.Id) + .FirstOrDefaultAsync(); + + if (@interface.Gateways is not null && @interface.Gateways.Any()) + { + foreach (var gateway in @interface.Gateways) + { + var gatewayFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var gatewayResult = await _database.HostInterfaceGateway().BulkWriteAsync(gatewayBulk, cancellationToken: cancellationToken); - } - - // nameservers - - if (interfaces is not null && interfaces.Any()) - { - var nameserverBulk = new List>(); - - foreach (var @interface in interfaces) - { - var interfaceId = await _database.HostInterface() - .Find(p => p.Host == hostEntity.Id && p.Index == @interface.Index) - .Project(p => p.Id) - .FirstOrDefaultAsync(); - - if (@interface.Dns is not null && @interface.Dns.Any()) - { - foreach (var nameserver in @interface.Dns) - { - var nameserverFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Interface, interfaceId), - Builders.Filter.Eq(x => x.Address, nameserver?.Address) - }); - - var nameserverUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Interface, interfaceId) - .SetOnInsert(p => p.Address, nameserver?.Address) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch); - - nameserverBulk.Add(new UpdateOneModel(nameserverFilter, nameserverUpdate) - { - IsUpsert = true + Builders.Filter.Eq(x => x.Interface, interfaceId), + Builders.Filter.Eq(x => x.Address, gateway?.Address) }); - } + + var gatewayUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Interface, interfaceId) + .SetOnInsert(p => p.Address, gateway?.Address) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch); + + gatewayBulk.Add(new UpdateOneModel(gatewayFilter, gatewayUpdate) + { + IsUpsert = true + }); } } + } - nameserverBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + gatewayBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var gatewayResult = await _database.HostInterfaceGateway().BulkWriteAsync(gatewayBulk, cancellationToken: cancellationToken); + } + + // nameservers + + if (interfaces is not null && interfaces.Any()) + { + var nameserverBulk = new List>(); + + foreach (var @interface in interfaces) + { + var interfaceId = await _database.HostInterface() + .Find(p => p.Host == hostEntity.Id && p.Index == @interface.Index) + .Project(p => p.Id) + .FirstOrDefaultAsync(); + + if (@interface.Dns is not null && @interface.Dns.Any()) + { + foreach (var nameserver in @interface.Dns) + { + var nameserverFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var nameserverResult = await _database.HostInterfaceNameserver().BulkWriteAsync(nameserverBulk, cancellationToken: cancellationToken); - } - - // routes - - if (interfaces is not null && interfaces.Any()) - { - var routeBulk = new List>(); - - foreach (var @interface in interfaces) - { - var interfaceId = await _database.HostInterface() - .Find(p => p.Host == hostEntity.Id && p.Index == @interface.Index) - .Project(p => p.Id) - .FirstOrDefaultAsync(); - - if (@interface.Routes is not null && @interface.Routes.Any()) - { - foreach (var route in @interface.Routes) - { - var routeFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Interface, interfaceId), - Builders.Filter.Eq(x => x.Destination, route?.Destination?.Address), - Builders.Filter.Eq(x => x.Gateway, route?.Gateway?.Address), - Builders.Filter.Eq(x => x.Mask, route?.Mask), - }); - - var routeUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Interface, interfaceId) - .SetOnInsert(p => p.Destination, route?.Destination?.Address) - .SetOnInsert(p => p.Gateway, route?.Gateway?.Address) - .SetOnInsert(p => p.Mask, route?.Mask) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - - .Set(p => p.Metric, route?.Metric); - - routeBulk.Add(new UpdateOneModel(routeFilter, routeUpdate) - { - IsUpsert = true + Builders.Filter.Eq(x => x.Interface, interfaceId), + Builders.Filter.Eq(x => x.Address, nameserver?.Address) }); - } + + var nameserverUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Interface, interfaceId) + .SetOnInsert(p => p.Address, nameserver?.Address) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch); + + nameserverBulk.Add(new UpdateOneModel(nameserverFilter, nameserverUpdate) + { + IsUpsert = true + }); } } + } - routeBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + nameserverBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var nameserverResult = await _database.HostInterfaceNameserver().BulkWriteAsync(nameserverBulk, cancellationToken: cancellationToken); + } + + // routes + + if (interfaces is not null && interfaces.Any()) + { + var routeBulk = new List>(); + + foreach (var @interface in interfaces) + { + var interfaceId = await _database.HostInterface() + .Find(p => p.Host == hostEntity.Id && p.Index == @interface.Index) + .Project(p => p.Id) + .FirstOrDefaultAsync(); + + if (@interface.Routes is not null && @interface.Routes.Any()) + { + foreach (var route in @interface.Routes) + { + var routeFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); + Builders.Filter.Eq(x => x.Interface, interfaceId), + Builders.Filter.Eq(x => x.Destination, route?.Destination?.Address), + Builders.Filter.Eq(x => x.Gateway, route?.Gateway?.Address), + Builders.Filter.Eq(x => x.Mask, route?.Mask), + }); - var routeResult = await _database.HostInterfaceRoute().BulkWriteAsync(routeBulk, cancellationToken: cancellationToken); + var routeUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Interface, interfaceId) + .SetOnInsert(p => p.Destination, route?.Destination?.Address) + .SetOnInsert(p => p.Gateway, route?.Gateway?.Address) + .SetOnInsert(p => p.Mask, route?.Mask) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + + .Set(p => p.Metric, route?.Metric); + + routeBulk.Add(new UpdateOneModel(routeFilter, routeUpdate) + { + IsUpsert = true + }); + } + } } + + routeBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var routeResult = await _database.HostInterfaceRoute().BulkWriteAsync(routeBulk, cancellationToken: cancellationToken); } } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/MainboardHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/MainboardHandler.cs index 10e6121..99e5dfc 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/MainboardHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/MainboardHandler.cs @@ -1,12 +1,13 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Driver; namespace Insight.Server.Network.Handlers.Agent { - public class MainboardHandler : IAgentMessageHandler + public class MainboardHandler : IMessageHandler { private readonly IMongoDatabase _database; @@ -15,7 +16,7 @@ namespace Insight.Server.Network.Handlers.Agent _database = database; } - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage { if (message is Mainboard mainboard) { diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/MemoryHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/MemoryHandler.cs index 99d78cd..7c02e92 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/MemoryHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/MemoryHandler.cs @@ -1,83 +1,83 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class MemoryHandler : IMessageHandler { - public class MemoryHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public MemoryHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public MemoryHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is MemoryList memory) { - _database = database; - } - - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is MemoryList memory) - { - await OnMemoryAsync(sender, memory, cancellationToken); - } - } - - private async ValueTask OnMemoryAsync(AgentSession session, List memory, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - var bulk = new List>(); - - if (memory is not null && memory.Any()) - { - foreach (var mem in memory) - { - var filterDefinition = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Index, mem.Index) - }); - - var updateDefinition = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Index, mem.Index) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - .Set(p => p.Company, mem.Manufacturer) - .Set(p => p.Name, mem.Model) - .Set(p => p.Tag, mem.Tag) - .Set(p => p.Location, mem.Location) - .Set(p => p.Serial, mem.Serial) - .Set(p => p.Capacity, mem.Capacity) - .Set(p => p.Clock, mem.Speed) - .Set(p => p.CurrentClock, mem.ConfiguredSpeed) - .Set(p => p.Voltage, mem.Voltage) - .Set(p => p.CurrentVoltage, mem.ConfiguredVoltage); - - bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) - { - IsUpsert = true - }); - } - } - - bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var result = await _database.HostMemory().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + await OnMemoryAsync(sender, memory, cancellationToken); } } + + private async ValueTask OnMemoryAsync(AgentSession session, List memory, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + var bulk = new List>(); + + if (memory is not null && memory.Any()) + { + foreach (var mem in memory) + { + var filterDefinition = Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Eq(x => x.Index, mem.Index) + }); + + var updateDefinition = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Index, mem.Index) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + .Set(p => p.Company, mem.Manufacturer) + .Set(p => p.Name, mem.Model) + .Set(p => p.Tag, mem.Tag) + .Set(p => p.Location, mem.Location) + .Set(p => p.Serial, mem.Serial) + .Set(p => p.Capacity, mem.Capacity) + .Set(p => p.Clock, mem.Speed) + .Set(p => p.CurrentClock, mem.ConfiguredSpeed) + .Set(p => p.Voltage, mem.Voltage) + .Set(p => p.CurrentVoltage, mem.ConfiguredVoltage); + + bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) + { + IsUpsert = true + }); + } + } + + bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var result = await _database.HostMemory().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/OperationSystemHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/OperationSystemHandler.cs index ca8743e..9f274c1 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/OperationSystemHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/OperationSystemHandler.cs @@ -1,51 +1,51 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class OperationSystemHandler : IMessageHandler { - public class OperationSystemHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public OperationSystemHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public OperationSystemHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is OperationSystem os) { - _database = database; - } - - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is OperationSystem os) - { - await OnOperationSystemAsync(sender, os, cancellationToken); - } - } - - private async ValueTask OnOperationSystemAsync(AgentSession session, OperationSystem operatingSystem, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var date = DateTime.Now; - - await _database.HostOs().UpdateOneAsync(p => p.Host == hostEntity.Id, Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .Set(p => p.Update, date) - .Set(p => p.Name, operatingSystem.Name) - .Set(p => p.Version, operatingSystem.Version) - .Set(p => p.Architecture, operatingSystem.Architecture.ToString()) - .Set(p => p.SerialNumber, operatingSystem.SerialNumber) - .Set(p => p.Virtual, operatingSystem.Virtual) - .Set(p => p.Installed, operatingSystem.InstallDate), new UpdateOptions - { - IsUpsert = true - }, cancellationToken); + await OnOperationSystemAsync(sender, os, cancellationToken); } } + + private async ValueTask OnOperationSystemAsync(AgentSession session, OperationSystem operatingSystem, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var date = DateTime.Now; + + await _database.HostOs().UpdateOneAsync(p => p.Host == hostEntity.Id, Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .Set(p => p.Update, date) + .Set(p => p.Name, operatingSystem.Name) + .Set(p => p.Version, operatingSystem.Version) + .Set(p => p.Architecture, operatingSystem.Architecture.ToString()) + .Set(p => p.SerialNumber, operatingSystem.SerialNumber) + .Set(p => p.Virtual, operatingSystem.Virtual) + .Set(p => p.Installed, operatingSystem.InstallDate), new UpdateOptions + { + IsUpsert = true + }, cancellationToken); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/PrinterHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/PrinterHandler.cs index eed8b2c..18d5694 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/PrinterHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/PrinterHandler.cs @@ -1,76 +1,76 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class PrinterHandler : IMessageHandler { - public class PrinterHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public PrinterHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public PrinterHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is PrinterList printers) { - _database = database; - } - - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is PrinterList printers) - { - await OnPrintersAsync(sender, printers, cancellationToken); - } - } - - private async ValueTask OnPrintersAsync(AgentSession session, List printers, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - var bulk = new List>(); - - if (printers is not null && printers.Any()) - { - foreach (var printer in printers) - { - var filterDefinition = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Name, printer.Name) - }); - - var updateDefinition = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Name, printer.Name) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - .Set(p => p.Port, printer.Port) - .Set(p => p.Location, printer.Location) - .Set(p => p.Comment, printer.Comment); - - bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) - { - IsUpsert = true - }); - } - } - - bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var result = await _database.HostPrinter().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + await OnPrintersAsync(sender, printers, cancellationToken); } } + + private async ValueTask OnPrintersAsync(AgentSession session, List printers, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + var bulk = new List>(); + + if (printers is not null && printers.Any()) + { + foreach (var printer in printers) + { + var filterDefinition = Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Eq(x => x.Name, printer.Name) + }); + + var updateDefinition = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Name, printer.Name) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + .Set(p => p.Port, printer.Port) + .Set(p => p.Location, printer.Location) + .Set(p => p.Comment, printer.Comment); + + bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) + { + IsUpsert = true + }); + } + } + + bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var result = await _database.HostPrinter().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/ProcessorHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/ProcessorHandler.cs index a4f9c5d..81befab 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/ProcessorHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/ProcessorHandler.cs @@ -1,87 +1,87 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class ProcessorHandler : IMessageHandler { - public class ProcessorHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public ProcessorHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public ProcessorHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is ProcessorList processors) { - _database = database; - } - - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is ProcessorList processors) - { - await OnProcessorsAsync(sender, processors, cancellationToken); - } - } - - private async ValueTask OnProcessorsAsync(AgentSession session, List processors, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - var bulk = new List>(); - - if (processors is not null && processors.Any()) - { - foreach (var processor in processors) - { - var filterDefinition = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Index, processor.Index) - }); - - var updateDefinition = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Index, processor.Index) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - .Set(p => p.Company, processor.Manufacturer) - .Set(p => p.Name, processor.Name) - .Set(p => p.Socket, processor.Socket) - .Set(p => p.Serial, processor.SerialNumber) - .Set(p => p.Version, processor.Version) - .Set(p => p.Cores, processor.Cores) - .Set(p => p.LogicalCores, processor.LogicalCores) - .Set(p => p.Clock, processor.MaxSpeed) - .Set(p => p.CurrentClock, processor.CurrentSpeed) - .Set(p => p.L1Size, processor.L1Size) - .Set(p => p.L2Size, processor.L2Size) - .Set(p => p.L3Size, processor.L3Size) - .Set(p => p.Virtualization, processor.Virtualization) - .Set(p => p.PNP, processor.DeviceId); - - bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) - { - IsUpsert = true - }); - } - } - - bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var result = await _database.HostProcessor().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + await OnProcessorsAsync(sender, processors, cancellationToken); } } + + private async ValueTask OnProcessorsAsync(AgentSession session, List processors, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + var bulk = new List>(); + + if (processors is not null && processors.Any()) + { + foreach (var processor in processors) + { + var filterDefinition = Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Eq(x => x.Index, processor.Index) + }); + + var updateDefinition = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Index, processor.Index) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + .Set(p => p.Company, processor.Manufacturer) + .Set(p => p.Name, processor.Name) + .Set(p => p.Socket, processor.Socket) + .Set(p => p.Serial, processor.SerialNumber) + .Set(p => p.Version, processor.Version) + .Set(p => p.Cores, processor.Cores) + .Set(p => p.LogicalCores, processor.LogicalCores) + .Set(p => p.Clock, processor.MaxSpeed) + .Set(p => p.CurrentClock, processor.CurrentSpeed) + .Set(p => p.L1Size, processor.L1Size) + .Set(p => p.L2Size, processor.L2Size) + .Set(p => p.L3Size, processor.L3Size) + .Set(p => p.Virtualization, processor.Virtualization) + .Set(p => p.PNP, processor.DeviceId); + + bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) + { + IsUpsert = true + }); + } + } + + bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var result = await _database.HostProcessor().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/ServiceHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/ServiceHandler.cs index 1108236..2aee03f 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/ServiceHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/ServiceHandler.cs @@ -1,81 +1,81 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class ServiceHandler : IMessageHandler { - public class ServiceHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public ServiceHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public ServiceHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is ServiceList services) { - _database = database; - } - - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is ServiceList services) - { - await OnServicesAsync(sender, services, cancellationToken); - } - } - - private async ValueTask OnServicesAsync(AgentSession session, List services, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - var bulk = new List>(); - - if (services is not null && services.Any()) - { - foreach (var service in services) - { - var filterDefinition = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Name, service.Name) - }); - - var updateDefinition = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Name, service.Name) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - .Set(p => p.DisplayName, service.Display) - .Set(p => p.Description, service.Description) - .Set(p => p.StartMode, service.StartMode.ToString()) - .Set(p => p.State, service.Status.ToString()) - .Set(p => p.ProcessId, service.ProcessId) - .Set(p => p.Delay, service.Delay) - .Set(p => p.Path, service.PathName) - .Set(p => p.Account, service.Account); - - bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) - { - IsUpsert = true - }); - } - } - - bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var result = await _database.HostService().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + await OnServicesAsync(sender, services, cancellationToken); } } + + private async ValueTask OnServicesAsync(AgentSession session, List services, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + var bulk = new List>(); + + if (services is not null && services.Any()) + { + foreach (var service in services) + { + var filterDefinition = Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Eq(x => x.Name, service.Name) + }); + + var updateDefinition = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Name, service.Name) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + .Set(p => p.DisplayName, service.Display) + .Set(p => p.Description, service.Description) + .Set(p => p.StartMode, service.StartMode.ToString()) + .Set(p => p.State, service.Status.ToString()) + .Set(p => p.ProcessId, service.ProcessId) + .Set(p => p.Delay, service.Delay) + .Set(p => p.Path, service.PathName) + .Set(p => p.Account, service.Account); + + bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) + { + IsUpsert = true + }); + } + } + + bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var result = await _database.HostService().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/SessionHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/SessionHandler.cs index ffad33d..c7c9bf3 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/SessionHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/SessionHandler.cs @@ -1,77 +1,77 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class SessionHandler : IMessageHandler { - public class SessionHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public SessionHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public SessionHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is SessionList sessions) { - _database = database; - } - - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is SessionList sessions) - { - await OnSessionsAsync(sender, sessions, cancellationToken); - } - } - - private async ValueTask OnSessionsAsync(AgentSession session, List sessions, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - var bulk = new List>(); - - if (sessions is not null && sessions.Any()) - { - foreach (var sess in sessions) - { - var filterDefinition = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Sid, sess.Sid) - }); - - var updateDefinition = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Sid, sess.Sid) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - .Set(p => p.User, sess.User) - .Set(p => p.Remote, sess.Remote) - .Set(p => p.Type, sess.Type) - .Set(p => p.State, sess.Status); - - bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) - { - IsUpsert = true - }); - } - } - - bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var result = await _database.HostSession().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + await OnSessionsAsync(sender, sessions, cancellationToken); } } + + private async ValueTask OnSessionsAsync(AgentSession session, List sessions, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + var bulk = new List>(); + + if (sessions is not null && sessions.Any()) + { + foreach (var sess in sessions) + { + var filterDefinition = Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Eq(x => x.Sid, sess.Sid) + }); + + var updateDefinition = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Sid, sess.Sid) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + .Set(p => p.User, sess.User) + .Set(p => p.Remote, sess.Remote) + .Set(p => p.Type, sess.Type) + .Set(p => p.State, sess.Status); + + bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) + { + IsUpsert = true + }); + } + } + + bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var result = await _database.HostSession().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/SoftwareHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/SoftwareHandler.cs index 1e986fa..36e1853 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/SoftwareHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/SoftwareHandler.cs @@ -1,78 +1,78 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class SoftwareHandler : IMessageHandler { - public class SoftwareHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public SoftwareHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public SoftwareHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is ApplicationList applications) { - _database = database; - } - - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is ApplicationList applications) - { - await OnApplicationsAsync(sender, applications, cancellationToken); - } - } - - private async ValueTask OnApplicationsAsync(AgentSession session, List applications, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - var bulk = new List>(); - - if (applications is not null && applications.Any()) - { - foreach (var app in applications) - { - var filterDefinition = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Name, app.Name), - Builders.Filter.Eq(x => x.Architecture, app.Architecture?.ToString()) - }); - - var updateDefinition = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Name, app.Name) - .SetOnInsert(p => p.Architecture, app.Architecture?.ToString()) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - .Set(p => p.Company, app.Publisher) - .Set(p => p.Version, app.Version) - .Set(p => p.InstallDate, app.InstallDate); - - bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) - { - IsUpsert = true - }); - } - } - - bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var result = await _database.HostApplication().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + await OnApplicationsAsync(sender, applications, cancellationToken); } } + + private async ValueTask OnApplicationsAsync(AgentSession session, List applications, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + var bulk = new List>(); + + if (applications is not null && applications.Any()) + { + foreach (var app in applications) + { + var filterDefinition = Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Eq(x => x.Name, app.Name), + Builders.Filter.Eq(x => x.Architecture, app.Architecture?.ToString()) + }); + + var updateDefinition = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Name, app.Name) + .SetOnInsert(p => p.Architecture, app.Architecture?.ToString()) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + .Set(p => p.Company, app.Publisher) + .Set(p => p.Version, app.Version) + .Set(p => p.InstallDate, app.InstallDate); + + bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) + { + IsUpsert = true + }); + } + } + + bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var result = await _database.HostApplication().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/StoragePoolHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/StoragePoolHandler.cs index 7b00c9c..3085a14 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/StoragePoolHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/StoragePoolHandler.cs @@ -1,253 +1,253 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class StoragePoolHandler : IMessageHandler { - public class StoragePoolHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public StoragePoolHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public StoragePoolHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is StoragePoolList storagePools) { - _database = database; + await OnStoragePoolsAsync(sender, storagePools, cancellationToken); } + } - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + private async ValueTask OnStoragePoolsAsync(AgentSession session, List? storagePools, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + // storagepools + + if (storagePools is not null && storagePools.Any()) { - if (message is StoragePoolList storagePools) + var storagepoolBulk = new List>(); + + foreach (var storagePool in storagePools) { - await OnStoragePoolsAsync(sender, storagePools, cancellationToken); - } - } - - private async ValueTask OnStoragePoolsAsync(AgentSession session, List? storagePools, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - // storagepools - - if (storagePools is not null && storagePools.Any()) - { - var storagepoolBulk = new List>(); - - foreach (var storagePool in storagePools) - { - var storagePoolFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.UniqueId, storagePool.UniqueId) - }); - - List? states = null; - - if (storagePool.States is not null) - { - states = new List(); - - foreach (var state in storagePool.States) - { - states.Add(state.ToString()); - } - } - - var storagePoolUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.UniqueId, storagePool.UniqueId) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - - .Set(p => p.Name, storagePool.FriendlyName) - .Set(p => p.Health, storagePool.Health?.ToString()) - .Set(p => p.Resiliency, storagePool.Resiliency) - .Set(p => p.Primordial, storagePool.IsPrimordial) - .Set(p => p.ReadOnly, storagePool.IsReadOnly) - .Set(p => p.Clustered, storagePool.IsClustered) - .Set(p => p.Size, storagePool.Size) - .Set(p => p.AllocatedSize, storagePool.AllocatedSize) - .Set(p => p.SectorSize, storagePool.SectorSize) - .Set(p => p.States, states); - - storagepoolBulk.Add(new UpdateOneModel(storagePoolFilter, storagePoolUpdate) - { - IsUpsert = true - }); - } - - storagepoolBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + var storagePoolFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); + Builders.Filter.Eq(x => x.UniqueId, storagePool.UniqueId) + }); - var storagePoolResult = await _database.HostStoragePool().BulkWriteAsync(storagepoolBulk, cancellationToken: cancellationToken); - } + List? states = null; - // physicaldisks - - if (storagePools is not null && storagePools.Any()) - { - var physicalDiskBulk = new List>(); - - foreach (var storagePool in storagePools) + if (storagePool.States is not null) { - var storagePoolId = await _database.HostStoragePool() - .Find(p => p.Host == hostEntity.Id && p.UniqueId == storagePool.UniqueId) - .Project(p => p.Id) - .FirstOrDefaultAsync(); + states = new List(); - if (storagePool.PhysicalDisks is not null && storagePool.PhysicalDisks.Any()) + foreach (var state in storagePool.States) { - foreach (var physicalDisk in storagePool.PhysicalDisks) - { - var physicalDiskFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.StoragePool, storagePoolId), - Builders.Filter.Eq(x => x.UniqueId, physicalDisk.UniqueId) - }); - - List? states = null; - - if (physicalDisk.States is not null) - { - states = new List(); - - foreach (var state in physicalDisk.States) - { - states.Add(state.ToString()); - } - } - - var physicalDiskUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.StoragePool, storagePoolId) - .SetOnInsert(p => p.UniqueId, physicalDisk.UniqueId) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - - .Set(p => p.DeviceId, physicalDisk.DeviceId) - .Set(p => p.Name, physicalDisk.FriendlyName) - .Set(p => p.Manufacturer, physicalDisk.Manufacturer) - .Set(p => p.Model, physicalDisk.Model) - .Set(p => p.Media, physicalDisk.MediaType.ToString()) - .Set(p => p.Bus, physicalDisk.BusType.ToString()) - .Set(p => p.Health, physicalDisk.Health.ToString()) - .Set(p => p.Usage, physicalDisk.Usage) - .Set(p => p.Location, physicalDisk.PhysicalLocation) - .Set(p => p.Serial, physicalDisk.SerialNumber) - .Set(p => p.Firmware, physicalDisk.FirmwareVersion) - .Set(p => p.Size, physicalDisk.Size) - .Set(p => p.AllocatedSize, physicalDisk.AllocatedSize) - .Set(p => p.Footprint, physicalDisk.VirtualDiskFootprint) - .Set(p => p.LogicalSectorSize, physicalDisk.LogicalSectorSize) - .Set(p => p.PhysicalSectorSize, physicalDisk.PhysicalSectorSize) - .Set(p => p.States, states); - - physicalDiskBulk.Add(new UpdateOneModel(physicalDiskFilter, physicalDiskUpdate) - { - IsUpsert = true - }); - } + states.Add(state.ToString()); } } - physicalDiskBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + var storagePoolUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.UniqueId, storagePool.UniqueId) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + + .Set(p => p.Name, storagePool.FriendlyName) + .Set(p => p.Health, storagePool.Health?.ToString()) + .Set(p => p.Resiliency, storagePool.Resiliency) + .Set(p => p.Primordial, storagePool.IsPrimordial) + .Set(p => p.ReadOnly, storagePool.IsReadOnly) + .Set(p => p.Clustered, storagePool.IsClustered) + .Set(p => p.Size, storagePool.Size) + .Set(p => p.AllocatedSize, storagePool.AllocatedSize) + .Set(p => p.SectorSize, storagePool.SectorSize) + .Set(p => p.States, states); + + storagepoolBulk.Add(new UpdateOneModel(storagePoolFilter, storagePoolUpdate) + { + IsUpsert = true + }); + } + + storagepoolBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var storagePoolResult = await _database.HostStoragePool().BulkWriteAsync(storagepoolBulk, cancellationToken: cancellationToken); + } + + // physicaldisks + + if (storagePools is not null && storagePools.Any()) + { + var physicalDiskBulk = new List>(); + + foreach (var storagePool in storagePools) + { + var storagePoolId = await _database.HostStoragePool() + .Find(p => p.Host == hostEntity.Id && p.UniqueId == storagePool.UniqueId) + .Project(p => p.Id) + .FirstOrDefaultAsync(); + + if (storagePool.PhysicalDisks is not null && storagePool.PhysicalDisks.Any()) + { + foreach (var physicalDisk in storagePool.PhysicalDisks) + { + var physicalDiskFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var physicalDiskResult = await _database.HostStoragePoolPhysicalDisk().BulkWriteAsync(physicalDiskBulk, cancellationToken: cancellationToken); - } - - // virtual disks - - if (storagePools is not null && storagePools.Any()) - { - var virtualDiskBulk = new List>(); - - foreach (var storagePool in storagePools) - { - if (storagePool.VirtualDisks is not null && storagePool.VirtualDisks.Any()) - { - foreach (var virtualDisk in storagePool.VirtualDisks) - { - var storagePoolId = await _database.HostStoragePool() - .Find(p => p.Host == hostEntity.Id && p.UniqueId == storagePool.UniqueId) - .Project(p => p.Id) - .FirstOrDefaultAsync(); - - var virtualDiskFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.StoragePool, storagePoolId), - Builders.Filter.Eq(x => x.UniqueId, virtualDisk.UniqueId) - }); - - List? states = null; - - if (virtualDisk.States is not null) - { - states = new List(); - - foreach (var state in virtualDisk.States) - { - states.Add(state.ToString()); - } - } - - var virtualDiskUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.StoragePool, storagePoolId) - .SetOnInsert(p => p.UniqueId, virtualDisk.UniqueId) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - - .Set(p => p.Name, virtualDisk.FriendlyName) - .Set(p => p.Health, virtualDisk.Health.ToString()) - .Set(p => p.Access, virtualDisk.AccessType.ToString()) - .Set(p => p.Provisioning, virtualDisk.ProvisioningType.ToString()) - .Set(p => p.PhysicalRedundancy, virtualDisk.PhysicalDiskRedundancy) - .Set(p => p.Resiliency, virtualDisk.ResiliencySettingName) - .Set(p => p.Deduplication, virtualDisk.Deduplication) - .Set(p => p.Snapshot, virtualDisk.IsSnapshot) - .Set(p => p.Size, virtualDisk.Size) - .Set(p => p.AllocatedSize, virtualDisk.AllocatedSize) - .Set(p => p.Footprint, virtualDisk.FootprintOnPool) - .Set(p => p.ReadCacheSize, virtualDisk.ReadCacheSize) - .Set(p => p.WriteCacheSize, virtualDisk.WriteCacheSize) - .Set(p => p.States, states); - - virtualDiskBulk.Add(new UpdateOneModel(virtualDiskFilter, virtualDiskUpdate) - { - IsUpsert = true + Builders.Filter.Eq(x => x.StoragePool, storagePoolId), + Builders.Filter.Eq(x => x.UniqueId, physicalDisk.UniqueId) }); + + List? states = null; + + if (physicalDisk.States is not null) + { + states = new List(); + + foreach (var state in physicalDisk.States) + { + states.Add(state.ToString()); + } } + + var physicalDiskUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.StoragePool, storagePoolId) + .SetOnInsert(p => p.UniqueId, physicalDisk.UniqueId) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + + .Set(p => p.DeviceId, physicalDisk.DeviceId) + .Set(p => p.Name, physicalDisk.FriendlyName) + .Set(p => p.Manufacturer, physicalDisk.Manufacturer) + .Set(p => p.Model, physicalDisk.Model) + .Set(p => p.Media, physicalDisk.MediaType.ToString()) + .Set(p => p.Bus, physicalDisk.BusType.ToString()) + .Set(p => p.Health, physicalDisk.Health.ToString()) + .Set(p => p.Usage, physicalDisk.Usage) + .Set(p => p.Location, physicalDisk.PhysicalLocation) + .Set(p => p.Serial, physicalDisk.SerialNumber) + .Set(p => p.Firmware, physicalDisk.FirmwareVersion) + .Set(p => p.Size, physicalDisk.Size) + .Set(p => p.AllocatedSize, physicalDisk.AllocatedSize) + .Set(p => p.Footprint, physicalDisk.VirtualDiskFootprint) + .Set(p => p.LogicalSectorSize, physicalDisk.LogicalSectorSize) + .Set(p => p.PhysicalSectorSize, physicalDisk.PhysicalSectorSize) + .Set(p => p.States, states); + + physicalDiskBulk.Add(new UpdateOneModel(physicalDiskFilter, physicalDiskUpdate) + { + IsUpsert = true + }); } } + } - virtualDiskBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + physicalDiskBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var physicalDiskResult = await _database.HostStoragePoolPhysicalDisk().BulkWriteAsync(physicalDiskBulk, cancellationToken: cancellationToken); + } + + // virtual disks + + if (storagePools is not null && storagePools.Any()) + { + var virtualDiskBulk = new List>(); + + foreach (var storagePool in storagePools) + { + if (storagePool.VirtualDisks is not null && storagePool.VirtualDisks.Any()) + { + foreach (var virtualDisk in storagePool.VirtualDisks) + { + var storagePoolId = await _database.HostStoragePool() + .Find(p => p.Host == hostEntity.Id && p.UniqueId == storagePool.UniqueId) + .Project(p => p.Id) + .FirstOrDefaultAsync(); + + var virtualDiskFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); + Builders.Filter.Eq(x => x.StoragePool, storagePoolId), + Builders.Filter.Eq(x => x.UniqueId, virtualDisk.UniqueId) + }); - var virtualDiskResult = await _database.HostStoragePoolVirtualDisk().BulkWriteAsync(virtualDiskBulk, cancellationToken: cancellationToken); + List? states = null; + + if (virtualDisk.States is not null) + { + states = new List(); + + foreach (var state in virtualDisk.States) + { + states.Add(state.ToString()); + } + } + + var virtualDiskUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.StoragePool, storagePoolId) + .SetOnInsert(p => p.UniqueId, virtualDisk.UniqueId) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + + .Set(p => p.Name, virtualDisk.FriendlyName) + .Set(p => p.Health, virtualDisk.Health.ToString()) + .Set(p => p.Access, virtualDisk.AccessType.ToString()) + .Set(p => p.Provisioning, virtualDisk.ProvisioningType.ToString()) + .Set(p => p.PhysicalRedundancy, virtualDisk.PhysicalDiskRedundancy) + .Set(p => p.Resiliency, virtualDisk.ResiliencySettingName) + .Set(p => p.Deduplication, virtualDisk.Deduplication) + .Set(p => p.Snapshot, virtualDisk.IsSnapshot) + .Set(p => p.Size, virtualDisk.Size) + .Set(p => p.AllocatedSize, virtualDisk.AllocatedSize) + .Set(p => p.Footprint, virtualDisk.FootprintOnPool) + .Set(p => p.ReadCacheSize, virtualDisk.ReadCacheSize) + .Set(p => p.WriteCacheSize, virtualDisk.WriteCacheSize) + .Set(p => p.States, states); + + virtualDiskBulk.Add(new UpdateOneModel(virtualDiskFilter, virtualDiskUpdate) + { + IsUpsert = true + }); + } + } } + + virtualDiskBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var virtualDiskResult = await _database.HostStoragePoolVirtualDisk().BulkWriteAsync(virtualDiskBulk, cancellationToken: cancellationToken); } } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/SystemInfoHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/SystemInfoHandler.cs index 7abab05..82b0b2c 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/SystemInfoHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/SystemInfoHandler.cs @@ -1,49 +1,49 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class SystemInfoHandler : IMessageHandler { - public class SystemInfoHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public SystemInfoHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public SystemInfoHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is SystemInfo systemInfo) { - _database = database; - } - - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is SystemInfo systemInfo) - { - await OnSystemInfoAsync(sender, systemInfo, cancellationToken); - } - } - - private async ValueTask OnSystemInfoAsync(AgentSession session, SystemInfo? system, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var date = DateTime.Now; - - await _database.HostSystem().UpdateOneAsync(p => p.Host == hostEntity.Id, Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .Set(p => p.Update, date) - .Set(p => p.BootUpTime, system.LastBootUpTime) - .Set(p => p.LocalTime, system.LocalDateTime) - .Set(p => p.Processes, system.Processes) - .Set(p => p.License, system.License), new UpdateOptions - { - IsUpsert = true - }, cancellationToken); + await OnSystemInfoAsync(sender, systemInfo, cancellationToken); } } + + private async ValueTask OnSystemInfoAsync(AgentSession session, SystemInfo? system, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var date = DateTime.Now; + + await _database.HostSystem().UpdateOneAsync(p => p.Host == hostEntity.Id, Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .Set(p => p.Update, date) + .Set(p => p.BootUpTime, system.LastBootUpTime) + .Set(p => p.LocalTime, system.LocalDateTime) + .Set(p => p.Processes, system.Processes) + .Set(p => p.License, system.License), new UpdateOptions + { + IsUpsert = true + }, cancellationToken); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/TrapHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/TrapHandler.cs index 9d8b817..97649e2 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/TrapHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/TrapHandler.cs @@ -1,6 +1,7 @@ -using Insight.Agent.Enums; -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Enums; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using Insight.Server.Models; @@ -9,281 +10,280 @@ using System.Text; using System.Text.RegularExpressions; using static Insight.Server.Models.MonitorMessage; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class TrapHandler : IMessageHandler { - public class TrapHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public TrapHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public TrapHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is Trap trap) { - _database = database; + await OnTrapAsync(sender, trap, cancellationToken); + } + } + + private async ValueTask OnTrapAsync(AgentSession session, Trap? trap, CancellationToken cancellationToken) + { + if (trap is null) return; + + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + if (TryParse(trap, out var monitoring) is false) + { + //_logger.LogWarning($"Failed to parse"); } - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + // insert monitoring log + var monitoringLog = new HostLogMonitoringEntity { - if (message is Trap trap) - { - await OnTrapAsync(sender, trap, cancellationToken); - } + Host = hostEntity.Id, + Insert = DateTime.Now, + Timestamp = monitoring?.Timestamp, + Category = monitoring?.Category?.ToString(), + Status = monitoring?.Status?.ToString(), + Hostname = monitoring?.Hostname, + Task = monitoring?.Subject, + Message = monitoring?.Message, + Dispatch = DispatchEnum.Pending.ToString() + }; + + await _database.HostLogMonitoring() + .InsertOneAsync(monitoringLog, cancellationToken: cancellationToken); + + // insert host log + var log = new HostLogEntity + { + Insert = monitoringLog.Insert, + Host = monitoringLog.Host, + Category = monitoringLog.Category, + Status = monitoringLog.Status, + Source = "Trap", + Message = monitoringLog?.Task, + Timestamp = monitoringLog?.Insert + }; + + if (monitoringLog?.Message is not null) log.Message += $"\n{monitoringLog.Message}"; + + await _database.HostLog() + .InsertOneAsync(log, cancellationToken: cancellationToken) + .ConfigureAwait(false); + } + + private static bool TryParse(Trap packet, out MonitorMessage? monitoring) + { + monitoring = null; + + if (packet is null || packet.Data is null || packet.Data.Any() is false) return false; + + monitoring = new MonitorMessage + { + Community = packet.Community, + Category = CategoryEnum.Monitoring, + Endpoint = packet.Endpoint, + Timestamp = packet.Timestamp + }; + + if (Enum.TryParse(packet.Community, true, out var application)) + { + monitoring.Application = application; } - private async ValueTask OnTrapAsync(AgentSession session, Trap? trap, CancellationToken cancellationToken) + StatusEnum? status; + string? task; + string? message; + + switch (application) { - if (trap is null) return; - - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - if (TryParse(trap, out var monitoring) is false) - { - //_logger.LogWarning($"Failed to parse"); - } - - // insert monitoring log - var monitoringLog = new HostLogMonitoringEntity - { - Host = hostEntity.Id, - Insert = DateTime.Now, - Timestamp = monitoring?.Timestamp, - Category = monitoring?.Category?.ToString(), - Status = monitoring?.Status?.ToString(), - Hostname = monitoring?.Hostname, - Task = monitoring?.Subject, - Message = monitoring?.Message, - Dispatch = DispatchEnum.Pending.ToString() - }; - - await _database.HostLogMonitoring() - .InsertOneAsync(monitoringLog, cancellationToken: cancellationToken); - - // insert host log - var log = new HostLogEntity - { - Insert = monitoringLog.Insert, - Host = monitoringLog.Host, - Category = monitoringLog.Category, - Status = monitoringLog.Status, - Source = "Trap", - Message = monitoringLog?.Task, - Timestamp = monitoringLog?.Insert - }; - - if (monitoringLog?.Message is not null) log.Message += $"\n{monitoringLog.Message}"; - - await _database.HostLog() - .InsertOneAsync(log, cancellationToken: cancellationToken) - .ConfigureAwait(false); + case ApplicationEnum.Acronis: + monitoring.Application = ApplicationEnum.Acronis; + if (ParseAcronis(packet.Data, out status, out task, out message) is false) return false; + break; + case ApplicationEnum.Veeam: + monitoring.Application = ApplicationEnum.Veeam; + if (ParseVeeam(packet.Data, out status, out task, out message) is false) return false; + break; + case ApplicationEnum.QNAP: + monitoring.Application = ApplicationEnum.QNAP; + monitoring.Category = CategoryEnum.System; + monitoring.Hostname = packet.Hostname; + if (ParseQnap(packet.Data, out status, out task, out message) is false) return false; + break; + default: + return false; } - private static bool TryParse(Trap packet, out MonitorMessage? monitoring) + monitoring.Status = status; + monitoring.Subject = task; + monitoring.Message = message; + + return true; + } + + private static bool ParseAcronis(List> data, out StatusEnum? status, out string? task, out string? message) + { + status = data[0].Value.ToLower() switch { - monitoring = null; + "erfolgreich" => StatusEnum.Information, + "success" => StatusEnum.Information, + "information" => StatusEnum.Information, + "warnung" => StatusEnum.Warning, + "warning" => StatusEnum.Warning, + "fehler" => StatusEnum.Error, + "failed" => StatusEnum.Error, + "error" => StatusEnum.Error, + _ => null, + }; - if (packet is null || packet.Data is null || packet.Data.Any() is false) return false; + task = null; + message = null; - monitoring = new MonitorMessage - { - Community = packet.Community, - Category = CategoryEnum.Monitoring, - Endpoint = packet.Endpoint, - Timestamp = packet.Timestamp - }; + var parsed = false; - if (Enum.TryParse(packet.Community, true, out var application)) - { - monitoring.Application = application; - } + try + { + var trim = data[1].Value.Split(new string[] { ":" }, StringSplitOptions.None); + task = trim[1].Split(new string[] { "'" }, StringSplitOptions.None)[1].Split("'")[0].Trim(); + message = trim[1].Split(new string[] { "' " }, StringSplitOptions.None)[1].Trim(); - StatusEnum? status; - string? task; - string? message; - - switch (application) - { - case ApplicationEnum.Acronis: - monitoring.Application = ApplicationEnum.Acronis; - if (ParseAcronis(packet.Data, out status, out task, out message) is false) return false; - break; - case ApplicationEnum.Veeam: - monitoring.Application = ApplicationEnum.Veeam; - if (ParseVeeam(packet.Data, out status, out task, out message) is false) return false; - break; - case ApplicationEnum.QNAP: - monitoring.Application = ApplicationEnum.QNAP; - monitoring.Category = CategoryEnum.System; - monitoring.Hostname = packet.Hostname; - if (ParseQnap(packet.Data, out status, out task, out message) is false) return false; - break; - default: - return false; - } - - monitoring.Status = status; - monitoring.Subject = task; - monitoring.Message = message; - - return true; + parsed = true; + } + catch (Exception) + { + // skipped for base64 parse } - private static bool ParseAcronis(List> data, out StatusEnum? status, out string? task, out string? message) + if (parsed) return true; + + try { - status = data[0].Value.ToLower() switch + var content = Regex.Replace(data[1].Value, @"\s+", ""); + var bytes = Enumerable.Range(0, content.Length) + .Where(x => x % 2 == 0) + .Select(x => Convert.ToByte(content.Substring(x, 2), 16)) + .ToArray(); + + content = Encoding.UTF8.GetString(bytes); + + var trim = content.Split(new string[] { ":" }, StringSplitOptions.None); + task = trim[1].Split(new string[] { "'" }, StringSplitOptions.None)[1].Split("'")[0].Trim(); + message = trim[1].Split(new string[] { "' " }, StringSplitOptions.None)[1].Trim(); + + parsed = true; + } + catch (Exception ex) + { + //_logger.LogError("{ex}", ex); + } + + if (parsed) return true; + return false; + } + + private static bool ParseVeeam(List> data, out StatusEnum? status, out string? task, out string? message) + { + status = null; + task = null; + message = null; + + var parsed = false; + + try + { + var summary = false; + + if (Guid.TryParse(data[0].Value, out _)) + summary = true; + + if (data[1].Value.ToLower() == "backup configuration job") + return false; + + status = (summary ? data[2].Value.ToLower() : data[3].Value.ToLower()) switch { - "erfolgreich" => StatusEnum.Information, "success" => StatusEnum.Information, - "information" => StatusEnum.Information, - "warnung" => StatusEnum.Warning, "warning" => StatusEnum.Warning, - "fehler" => StatusEnum.Error, "failed" => StatusEnum.Error, "error" => StatusEnum.Error, _ => null, }; - task = null; - message = null; - - var parsed = false; - - try - { - var trim = data[1].Value.Split(new string[] { ":" }, StringSplitOptions.None); - task = trim[1].Split(new string[] { "'" }, StringSplitOptions.None)[1].Split("'")[0].Trim(); - message = trim[1].Split(new string[] { "' " }, StringSplitOptions.None)[1].Trim(); - - parsed = true; - } - catch (Exception) - { - // skipped for base64 parse - } - - if (parsed) return true; - - try - { - var content = Regex.Replace(data[1].Value, @"\s+", ""); - var bytes = Enumerable.Range(0, content.Length) - .Where(x => x % 2 == 0) - .Select(x => Convert.ToByte(content.Substring(x, 2), 16)) - .ToArray(); - - content = Encoding.UTF8.GetString(bytes); - - var trim = content.Split(new string[] { ":" }, StringSplitOptions.None); - task = trim[1].Split(new string[] { "'" }, StringSplitOptions.None)[1].Split("'")[0].Trim(); - message = trim[1].Split(new string[] { "' " }, StringSplitOptions.None)[1].Trim(); - - parsed = true; - } - catch (Exception ex) - { - //_logger.LogError("{ex}", ex); - } - - if (parsed) return true; - return false; + task = data[1].Value; + parsed = true; } - - private static bool ParseVeeam(List> data, out StatusEnum? status, out string? task, out string? message) + catch (Exception) { - status = null; - task = null; - message = null; - var parsed = false; - - try - { - var summary = false; - - if (Guid.TryParse(data[0].Value, out _)) - summary = true; - - if (data[1].Value.ToLower() == "backup configuration job") - return false; - - status = (summary ? data[2].Value.ToLower() : data[3].Value.ToLower()) switch - { - "success" => StatusEnum.Information, - "warning" => StatusEnum.Warning, - "failed" => StatusEnum.Error, - "error" => StatusEnum.Error, - _ => null, - }; - - task = data[1].Value; - parsed = true; - } - catch (Exception) - { - - } - - if (parsed) return true; - return false; } - private static bool ParseQnap(List> data, out StatusEnum? status, out string? task, out string? message) + if (parsed) return true; + return false; + } + + private static bool ParseQnap(List> data, out StatusEnum? status, out string? task, out string? message) + { + status = StatusEnum.Information; + task = null; + message = string.Empty; + + var parsed = false; + + try { - status = StatusEnum.Information; - task = null; - message = string.Empty; - - var parsed = false; - - try + var keywords = new Dictionary { - var keywords = new Dictionary - { - { "power", StatusEnum.Information }, - { "rights", StatusEnum.Information }, - { "added", StatusEnum.Information }, - { "changed", StatusEnum.Information }, - { "password", StatusEnum.Information }, - { "firmware", StatusEnum.Information }, - { "restarting", StatusEnum.Information }, - { "detected", StatusEnum.Warning }, - { "external", StatusEnum.Warning }, - { "threshold", StatusEnum.Warning }, - { "file system", StatusEnum.Warning }, - { "raid", StatusEnum.Warning }, - { "full", StatusEnum.Error }, - { "failure", StatusEnum.Error }, - { "failed", StatusEnum.Error }, - { "resyncing", StatusEnum.Error }, - { "degraded", StatusEnum.Error }, - { "error", StatusEnum.Error }, - { "without error", StatusEnum.Information }, - { "ncsi", StatusEnum.Information } - }; + { "power", StatusEnum.Information }, + { "rights", StatusEnum.Information }, + { "added", StatusEnum.Information }, + { "changed", StatusEnum.Information }, + { "password", StatusEnum.Information }, + { "firmware", StatusEnum.Information }, + { "restarting", StatusEnum.Information }, + { "detected", StatusEnum.Warning }, + { "external", StatusEnum.Warning }, + { "threshold", StatusEnum.Warning }, + { "file system", StatusEnum.Warning }, + { "raid", StatusEnum.Warning }, + { "full", StatusEnum.Error }, + { "failure", StatusEnum.Error }, + { "failed", StatusEnum.Error }, + { "resyncing", StatusEnum.Error }, + { "degraded", StatusEnum.Error }, + { "error", StatusEnum.Error }, + { "without error", StatusEnum.Information }, + { "ncsi", StatusEnum.Information } + }; - foreach (var key in keywords) - { - if (Regex.IsMatch(string.Concat(data).ToLowerInvariant(), $@"\b{key.Key}\b")) - { - status = key.Value; - } - } - - foreach (var kv in data) - { - message += kv.Value; - } - - parsed = true; - } - catch (Exception ex) + foreach (var key in keywords) { - //_logger.LogError("{ex}", ex); + if (Regex.IsMatch(string.Concat(data).ToLowerInvariant(), $@"\b{key.Key}\b")) + { + status = key.Value; + } } - if (parsed) return true; - return false; + foreach (var kv in data) + { + message += kv.Value; + } + + parsed = true; } + catch (Exception ex) + { + //_logger.LogError("{ex}", ex); + } + + if (parsed) return true; + return false; } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/UpdateHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/UpdateHandler.cs index f1fe72d..6129da6 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/UpdateHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/UpdateHandler.cs @@ -1,121 +1,121 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class UpdateHandler : IMessageHandler { - public class UpdateHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public UpdateHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public UpdateHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is UpdateList updates) { - _database = database; - } - - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage - { - if (message is UpdateList updates) - { - await OnUpdatesAsync(sender, updates, cancellationToken); - } - } - - private async ValueTask OnUpdatesAsync(AgentSession session, UpdateList updates, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - var bulk = new List>(); - - if (updates is not null) - { - if (updates.Installed is not null && updates.Installed.Any()) - { - foreach (var update in updates.Installed) - { - var filterDefinition = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Serial, update.Id) - }); - - var updateDefinition = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Serial, update.Id) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - - .Set(p => p.Pending, false) - .Set(p => p.Name, update.Name) - .Set(p => p.Description, update.Description) - .Set(p => p.SupportUrl, update.SupportUrl) - .Set(p => p.Result, update.Result.ToString()) - .Set(p => p.Date, update.Date); - - bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) - { - IsUpsert = true - }); - } - } - - if (updates.Pending is not null && updates.Pending.Any()) - { - foreach (var update in updates.Pending) - { - var filterDefinition = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Serial, update.Id) - }); - - var updateDefinition = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Serial, update.Id) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - - .Set(p => p.Pending, true) - .Set(p => p.Name, update.Name) - .Set(p => p.Description, update.Description) - .Set(p => p.SupportUrl, update.SupportUrl) - .Set(p => p.Result, update.Result?.ToString()) - - .Set(p => p.Type, update.Type.ToString()) - .Set(p => p.Size, update.Size) - .Set(p => p.IsDownloaded, update.IsDownloaded) - .Set(p => p.CanRequestUserInput, update.CanRequestUserInput) - .Set(p => p.RebootBehavior, update.RebootBehavior?.ToString()) - - .Set(p => p.Date, update.Date); - - bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) - { - IsUpsert = true - }); - } - } - } - - bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); - - var result = await _database.HostUpdate().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + await OnUpdatesAsync(sender, updates, cancellationToken); } } + + private async ValueTask OnUpdatesAsync(AgentSession session, UpdateList updates, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + var bulk = new List>(); + + if (updates is not null) + { + if (updates.Installed is not null && updates.Installed.Any()) + { + foreach (var update in updates.Installed) + { + var filterDefinition = Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Eq(x => x.Serial, update.Id) + }); + + var updateDefinition = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Serial, update.Id) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + + .Set(p => p.Pending, false) + .Set(p => p.Name, update.Name) + .Set(p => p.Description, update.Description) + .Set(p => p.SupportUrl, update.SupportUrl) + .Set(p => p.Result, update.Result.ToString()) + .Set(p => p.Date, update.Date); + + bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) + { + IsUpsert = true + }); + } + } + + if (updates.Pending is not null && updates.Pending.Any()) + { + foreach (var update in updates.Pending) + { + var filterDefinition = Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Eq(x => x.Serial, update.Id) + }); + + var updateDefinition = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Serial, update.Id) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + + .Set(p => p.Pending, true) + .Set(p => p.Name, update.Name) + .Set(p => p.Description, update.Description) + .Set(p => p.SupportUrl, update.SupportUrl) + .Set(p => p.Result, update.Result?.ToString()) + + .Set(p => p.Type, update.Type.ToString()) + .Set(p => p.Size, update.Size) + .Set(p => p.IsDownloaded, update.IsDownloaded) + .Set(p => p.CanRequestUserInput, update.CanRequestUserInput) + .Set(p => p.RebootBehavior, update.RebootBehavior?.ToString()) + + .Set(p => p.Date, update.Date); + + bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) + { + IsUpsert = true + }); + } + } + } + + bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var result = await _database.HostUpdate().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/UserHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/UserHandler.cs index 5e09d66..eb1d729 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/UserHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/UserHandler.cs @@ -1,188 +1,188 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class UserHandler : IMessageHandler { - public class UserHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public UserHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public UserHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is UserList users) { - _database = database; + await OnUsersAsync(sender, users, cancellationToken); } + } - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + private async ValueTask OnUsersAsync(AgentSession session, List? users, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + // users + + if (users is not null && users.Any()) { - if (message is UserList users) + var userBulk = new List>(); + + foreach (var user in users) { - await OnUsersAsync(sender, users, cancellationToken); - } - } - - private async ValueTask OnUsersAsync(AgentSession session, List? users, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - // users - - if (users is not null && users.Any()) - { - var userBulk = new List>(); - - foreach (var user in users) - { - var userFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Domain, user?.Domain), - Builders.Filter.Eq(x => x.Name, user?.Name) - }); - - var userUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Domain, user?.Domain) - .SetOnInsert(p => p.Name, user?.Name) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - - .Set(p => p.Sid, user?.Sid) - .Set(p => p.FullName, user?.FullName) - .Set(p => p.Description, user?.Description) - .Set(p => p.Status, user?.Status) - .Set(p => p.LocalAccount, user?.LocalAccount) - .Set(p => p.Disabled, user?.Disabled) - .Set(p => p.Lockout, user?.Lockout) - .Set(p => p.PasswordChangeable, user?.PasswordChangeable) - .Set(p => p.PasswordExpires, user?.PasswordExpires) - .Set(p => p.PasswordRequired, user?.PasswordRequired); - - userBulk.Add(new UpdateOneModel(userFilter, userUpdate) - { - IsUpsert = true - }); - } - - userBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + var userFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); + Builders.Filter.Eq(x => x.Domain, user?.Domain), + Builders.Filter.Eq(x => x.Name, user?.Name) + }); - var userResult = await _database.HostSystemUser().BulkWriteAsync(userBulk, cancellationToken: cancellationToken); + var userUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Domain, user?.Domain) + .SetOnInsert(p => p.Name, user?.Name) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + + .Set(p => p.Sid, user?.Sid) + .Set(p => p.FullName, user?.FullName) + .Set(p => p.Description, user?.Description) + .Set(p => p.Status, user?.Status) + .Set(p => p.LocalAccount, user?.LocalAccount) + .Set(p => p.Disabled, user?.Disabled) + .Set(p => p.Lockout, user?.Lockout) + .Set(p => p.PasswordChangeable, user?.PasswordChangeable) + .Set(p => p.PasswordExpires, user?.PasswordExpires) + .Set(p => p.PasswordRequired, user?.PasswordRequired); + + userBulk.Add(new UpdateOneModel(userFilter, userUpdate) + { + IsUpsert = true + }); } - // groups - - if (users is not null && users.Any()) - { - var groupBulk = new List>(); - - var distinctGroups = users.SelectMany(p => p.Groups) - .GroupBy(p => new { p?.Domain, p?.Name }) - .Select(p => p.First()); - - foreach (var group in distinctGroups) + userBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> { - var groupFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Domain, group?.Domain), - Builders.Filter.Eq(x => x.Name, group?.Name) - }); + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); - var groupUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Domain, group?.Domain) - .SetOnInsert(p => p.Name, group?.Name) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) + var userResult = await _database.HostSystemUser().BulkWriteAsync(userBulk, cancellationToken: cancellationToken); + } - .Set(p => p.Sid, group?.Sid) - .Set(p => p.Description, group?.Description) - .Set(p => p.LocalAccount, group?.LocalAccount); + // groups - groupBulk.Add(new UpdateOneModel(groupFilter, groupUpdate) - { - IsUpsert = true - }); - } + if (users is not null && users.Any()) + { + var groupBulk = new List>(); - groupBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + var distinctGroups = users.SelectMany(p => p.Groups) + .GroupBy(p => new { p?.Domain, p?.Name }) + .Select(p => p.First()); + + foreach (var group in distinctGroups) + { + var groupFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); + Builders.Filter.Eq(x => x.Domain, group?.Domain), + Builders.Filter.Eq(x => x.Name, group?.Name) + }); - var groupResult = await _database.HostSystemGroup().BulkWriteAsync(groupBulk, cancellationToken: cancellationToken); + var groupUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Domain, group?.Domain) + .SetOnInsert(p => p.Name, group?.Name) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + + .Set(p => p.Sid, group?.Sid) + .Set(p => p.Description, group?.Description) + .Set(p => p.LocalAccount, group?.LocalAccount); + + groupBulk.Add(new UpdateOneModel(groupFilter, groupUpdate) + { + IsUpsert = true + }); } - // relations - - if (users is not null && users.Any()) - { - var relationBulk = new List>(); - - foreach (var user in users) + groupBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> { - var userId = await _database.HostSystemUser() - .Find(p => p.Host == hostEntity.Id && p.Domain == user.Domain && p.Name == user.Name) - .Project(p => p.Id) - .FirstOrDefaultAsync(); + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); - if (user.Groups is not null && user.Groups.Any()) + var groupResult = await _database.HostSystemGroup().BulkWriteAsync(groupBulk, cancellationToken: cancellationToken); + } + + // relations + + if (users is not null && users.Any()) + { + var relationBulk = new List>(); + + foreach (var user in users) + { + var userId = await _database.HostSystemUser() + .Find(p => p.Host == hostEntity.Id && p.Domain == user.Domain && p.Name == user.Name) + .Project(p => p.Id) + .FirstOrDefaultAsync(); + + if (user.Groups is not null && user.Groups.Any()) + { + foreach (var group in user.Groups) { - foreach (var group in user.Groups) - { - var groupId = await _database.HostSystemGroup() - .Find(p => p.Host == hostEntity.Id && p.Domain == group.Domain && p.Name == group.Name) - .Project(p => p.Id) - .FirstOrDefaultAsync(); + var groupId = await _database.HostSystemGroup() + .Find(p => p.Host == hostEntity.Id && p.Domain == group.Domain && p.Name == group.Name) + .Project(p => p.Id) + .FirstOrDefaultAsync(); - var relationFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.User, userId), - Builders.Filter.Eq(x => x.Group, groupId) - }); - - var relationUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.User, userId) - .SetOnInsert(p => p.Group, groupId) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch); - - relationBulk.Add(new UpdateOneModel(relationFilter, relationUpdate) - { - IsUpsert = true - }); - } - } - } - - relationBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + var relationFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); + Builders.Filter.Eq(x => x.User, userId), + Builders.Filter.Eq(x => x.Group, groupId) + }); - var relationResult = await _database.HostSystemUserSystemGroup().BulkWriteAsync(relationBulk, cancellationToken: cancellationToken); + var relationUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.User, userId) + .SetOnInsert(p => p.Group, groupId) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch); + + relationBulk.Add(new UpdateOneModel(relationFilter, relationUpdate) + { + IsUpsert = true + }); + } + } } + + relationBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var relationResult = await _database.HostSystemUserSystemGroup().BulkWriteAsync(relationBulk, cancellationToken: cancellationToken); } } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/VideocardHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/VideocardHandler.cs index bf8e648..1637c5f 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/VideocardHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/VideocardHandler.cs @@ -1,77 +1,77 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class VideocardHandler : IMessageHandler { - public class VideocardHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public VideocardHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public VideocardHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is VideocardList videocards) { - _database = database; + await OnVideocardsAsync(sender, videocards, cancellationToken); } + } - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + private async ValueTask OnVideocardsAsync(AgentSession session, List? videocards, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + var bulk = new List>(); + + if (videocards is not null && videocards.Any()) { - if (message is VideocardList videocards) + foreach (var videocard in videocards) { - await OnVideocardsAsync(sender, videocards, cancellationToken); - } - } - - private async ValueTask OnVideocardsAsync(AgentSession session, List? videocards, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - var bulk = new List>(); - - if (videocards is not null && videocards.Any()) - { - foreach (var videocard in videocards) - { - var filterDefinition = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.Name, videocard.Model) - }); - - var updateDefinition = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.Name, videocard.Model) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - .Set(p => p.Company, null) - .Set(p => p.Memory, videocard.Memory) - .Set(p => p.Driver, videocard.DriverVersion) - .Set(p => p.Date, videocard.DriverDate); - - bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) - { - IsUpsert = true - }); - } - - bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + var filterDefinition = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); + Builders.Filter.Eq(x => x.Name, videocard.Model) + }); - var result = await _database.HostVideocard().BulkWriteAsync(bulk, cancellationToken: cancellationToken); + var updateDefinition = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.Name, videocard.Model) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + .Set(p => p.Company, null) + .Set(p => p.Memory, videocard.Memory) + .Set(p => p.Driver, videocard.DriverVersion) + .Set(p => p.Date, videocard.DriverDate); + + bulk.Add(new UpdateOneModel(filterDefinition, updateDefinition) + { + IsUpsert = true + }); } + + bulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var result = await _database.HostVideocard().BulkWriteAsync(bulk, cancellationToken: cancellationToken); } } } diff --git a/src/Server/Insight.Server/Network/Handlers/Agent/VirtualMaschineHandler.cs b/src/Server/Insight.Server/Network/Handlers/Agent/VirtualMaschineHandler.cs index a49e08d..220154b 100644 --- a/src/Server/Insight.Server/Network/Handlers/Agent/VirtualMaschineHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Agent/VirtualMaschineHandler.cs @@ -1,173 +1,173 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using MongoDB.Bson; using MongoDB.Driver; -namespace Insight.Server.Network.Handlers.Agent +namespace Insight.Server.Network.Handlers.Agent; + +public class VirtualMaschineHandler : IMessageHandler { - public class VirtualMaschineHandler : IAgentMessageHandler + private readonly IMongoDatabase _database; + + public VirtualMaschineHandler(IMongoDatabase database) { - private readonly IMongoDatabase _database; + _database = database; + } - public VirtualMaschineHandler(IMongoDatabase database) + public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is VirtualMaschineList virtualMaschines) { - _database = database; + await OnVirtualMaschinesAsync(sender, virtualMaschines, cancellationToken); } + } - public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage + private async ValueTask OnVirtualMaschinesAsync(AgentSession session, List? virtualMaschines, CancellationToken cancellationToken) + { + var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); + if (agentEntity is null) return; + + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return; + + var batch = ObjectId.GenerateNewId().ToString(); + var date = DateTime.Now; + + // virtual maschines + if (virtualMaschines is not null && virtualMaschines.Any()) { - if (message is VirtualMaschineList virtualMaschines) + var virtualMaschineBulk = new List>(); + + foreach (var virtualMaschine in virtualMaschines) { - await OnVirtualMaschinesAsync(sender, virtualMaschines, cancellationToken); - } - } - - private async ValueTask OnVirtualMaschinesAsync(AgentSession session, List? virtualMaschines, CancellationToken cancellationToken) - { - var agentEntity = await _database.Agent().Find(Builders.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken); - if (agentEntity is null) return; - - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return; - - var batch = ObjectId.GenerateNewId().ToString(); - var date = DateTime.Now; - - // virtual maschines - if (virtualMaschines is not null && virtualMaschines.Any()) - { - var virtualMaschineBulk = new List>(); - - foreach (var virtualMaschine in virtualMaschines) - { - var virtualMaschineFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.UniqueId, virtualMaschine.Id.ToString()) - }); - - var virtualMaschineUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.UniqueId, virtualMaschine.Id.ToString()) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - - .Set(p => p.Name, virtualMaschine?.Name) - .Set(p => p.Notes, virtualMaschine?.Notes) - .Set(p => p.Enabled, virtualMaschine?.Enabled?.ToString()) - .Set(p => p.EnabledDefault, virtualMaschine?.EnabledDefault?.ToString()) - .Set(p => p.Health, virtualMaschine?.HealthState?.ToString()) - .Set(p => p.Status, virtualMaschine?.Status) - .Set(p => p.OnTime, virtualMaschine?.OnTime) - .Set(p => p.ReplicationState, virtualMaschine?.ReplicationState?.ToString()) - .Set(p => p.ReplicationHealth, virtualMaschine?.ReplicationHealth?.ToString()) - .Set(p => p.ConfigurationVersion, virtualMaschine?.ConfigurationVersion) - .Set(p => p.IntegrationServicesVersionState, virtualMaschine?.IntegrationServicesVersionState?.ToString()) - .Set(p => p.ProcessId, virtualMaschine?.ProcessId) - .Set(p => p.NumberOfProcessors, virtualMaschine?.NumberOfProcessors) - .Set(p => p.ProcessorLoad, virtualMaschine?.ProcessorLoad) - .Set(p => p.MemoryAvailable, virtualMaschine?.MemoryAvailable) - .Set(p => p.MemoryUsage, virtualMaschine?.MemoryUsage) - .Set(p => p.InstallDate, virtualMaschine?.InstallDate) - .Set(p => p.ConfigurationVersion, virtualMaschine?.ConfigurationVersion) - .Set(p => p.TimeOfLastStateChange, virtualMaschine?.TimeOfLastStateChange) - .Set(p => p.LastReplicationTime, virtualMaschine?.LastReplicationTime) - .Set(p => p.Os, virtualMaschine?.GuestOperatingSystem); - - virtualMaschineBulk.Add(new UpdateOneModel(virtualMaschineFilter, virtualMaschineUpdate) - { - IsUpsert = true - }); - } - - virtualMaschineBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + var virtualMaschineFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); + Builders.Filter.Eq(x => x.UniqueId, virtualMaschine.Id.ToString()) + }); - var virtualMaschineResult = await _database.HostHypervisorVirtualMaschine().BulkWriteAsync(virtualMaschineBulk, cancellationToken: cancellationToken); + var virtualMaschineUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.UniqueId, virtualMaschine.Id.ToString()) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + + .Set(p => p.Name, virtualMaschine?.Name) + .Set(p => p.Notes, virtualMaschine?.Notes) + .Set(p => p.Enabled, virtualMaschine?.Enabled?.ToString()) + .Set(p => p.EnabledDefault, virtualMaschine?.EnabledDefault?.ToString()) + .Set(p => p.Health, virtualMaschine?.HealthState?.ToString()) + .Set(p => p.Status, virtualMaschine?.Status) + .Set(p => p.OnTime, virtualMaschine?.OnTime) + .Set(p => p.ReplicationState, virtualMaschine?.ReplicationState?.ToString()) + .Set(p => p.ReplicationHealth, virtualMaschine?.ReplicationHealth?.ToString()) + .Set(p => p.ConfigurationVersion, virtualMaschine?.ConfigurationVersion) + .Set(p => p.IntegrationServicesVersionState, virtualMaschine?.IntegrationServicesVersionState?.ToString()) + .Set(p => p.ProcessId, virtualMaschine?.ProcessId) + .Set(p => p.NumberOfProcessors, virtualMaschine?.NumberOfProcessors) + .Set(p => p.ProcessorLoad, virtualMaschine?.ProcessorLoad) + .Set(p => p.MemoryAvailable, virtualMaschine?.MemoryAvailable) + .Set(p => p.MemoryUsage, virtualMaschine?.MemoryUsage) + .Set(p => p.InstallDate, virtualMaschine?.InstallDate) + .Set(p => p.ConfigurationVersion, virtualMaschine?.ConfigurationVersion) + .Set(p => p.TimeOfLastStateChange, virtualMaschine?.TimeOfLastStateChange) + .Set(p => p.LastReplicationTime, virtualMaschine?.LastReplicationTime) + .Set(p => p.Os, virtualMaschine?.GuestOperatingSystem); + + virtualMaschineBulk.Add(new UpdateOneModel(virtualMaschineFilter, virtualMaschineUpdate) + { + IsUpsert = true + }); } - // virtual maschine configurations - - if (virtualMaschines is not null && virtualMaschines.Any()) - { - var configurationBulk = new List>(); - - foreach (var virtualmaschine in virtualMaschines) + virtualMaschineBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> { - var virtualMaschineId = await _database.HostHypervisorVirtualMaschine() - .Find(p => p.Host == hostEntity.Id && p.UniqueId == virtualmaschine.Id.ToString()) - .Project(p => p.Id) - .FirstOrDefaultAsync(); + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); - if (virtualmaschine.Configurations is not null && virtualmaschine.Configurations.Any()) + var virtualMaschineResult = await _database.HostHypervisorVirtualMaschine().BulkWriteAsync(virtualMaschineBulk, cancellationToken: cancellationToken); + } + + // virtual maschine configurations + + if (virtualMaschines is not null && virtualMaschines.Any()) + { + var configurationBulk = new List>(); + + foreach (var virtualmaschine in virtualMaschines) + { + var virtualMaschineId = await _database.HostHypervisorVirtualMaschine() + .Find(p => p.Host == hostEntity.Id && p.UniqueId == virtualmaschine.Id.ToString()) + .Project(p => p.Id) + .FirstOrDefaultAsync(); + + if (virtualmaschine.Configurations is not null && virtualmaschine.Configurations.Any()) + { + foreach (var config in virtualmaschine.Configurations) { - foreach (var config in virtualmaschine.Configurations) - { - var configFilter = Builders.Filter.And(new List> - { - Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Eq(x => x.VirtualMaschine, virtualMaschineId), - Builders.Filter.Eq(x => x.UniqueId, config.Id) - }); - - // custom "notes" concat - string notes = string.Empty; - if (config?.Notes is not null) foreach (var n in config.Notes) notes += n; - - var configUpdate = Builders.Update - .SetOnInsert(p => p.Insert, date) - .SetOnInsert(p => p.Host, hostEntity.Id) - .SetOnInsert(p => p.VirtualMaschine, virtualMaschineId) - .SetOnInsert(p => p.UniqueId, config.Id) - .Set(p => p.Update, date) - .Set(p => p.Batch, batch) - - .Set(p => p.ParentId, config.ParentId) - .Set(p => p.Type, config.Type) - .Set(p => p.Name, config.Name) - .Set(p => p.Notes, notes) - .Set(p => p.CreationTime, config.CreationTime) - .Set(p => p.Generation, config.Generation) - .Set(p => p.Architecture, config.Architecture) - .Set(p => p.SecureBootEnabled, config.SecureBootEnabled) - .Set(p => p.IsAutomaticSnapshot, config.IsAutomaticSnapshot) - .Set(p => p.AutomaticStartupAction, config.AutomaticStartupAction?.ToString()) - .Set(p => p.AutomaticShutdownAction, config.AutomaticShutdownAction?.ToString()) - .Set(p => p.AutomaticRecoveryAction, config.AutomaticRecoveryAction?.ToString()) - .Set(p => p.AutomaticSnapshotsEnabled, config.AutomaticSnapshotsEnabled) - .Set(p => p.BaseBoardSerialNumber, config.BaseBoardSerialNumber) - .Set(p => p.BIOSSerialNumber, config.BIOSSerialNumber) - .Set(p => p.BIOSGUID, config.BIOSGUID) - .Set(p => p.ConfigurationDataRoot, config.ConfigurationDataRoot) - .Set(p => p.ConfigurationFile, config.ConfigurationFile) - .Set(p => p.GuestStateDataRoot, config.GuestStateDataRoot) - .Set(p => p.GuestStateFile, config.GuestStateFile) - .Set(p => p.SnapshotDataRoot, config.SnapshotDataRoot) - .Set(p => p.SuspendDataRoot, config.SuspendDataRoot) - .Set(p => p.SwapFileDataRoot, config.SwapFileDataRoot); - - configurationBulk.Add(new UpdateOneModel(configFilter, configUpdate) - { - IsUpsert = true - }); - } - } - } - - configurationBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + var configFilter = Builders.Filter.And(new List> { Builders.Filter.Eq(x => x.Host, hostEntity.Id), - Builders.Filter.Ne(x => x.Batch, batch) - }))); + Builders.Filter.Eq(x => x.VirtualMaschine, virtualMaschineId), + Builders.Filter.Eq(x => x.UniqueId, config.Id) + }); - var configurationResult = await _database.HostVirtualMaschineConfig().BulkWriteAsync(configurationBulk, cancellationToken: cancellationToken); + // custom "notes" concat + string notes = string.Empty; + if (config?.Notes is not null) foreach (var n in config.Notes) notes += n; + + var configUpdate = Builders.Update + .SetOnInsert(p => p.Insert, date) + .SetOnInsert(p => p.Host, hostEntity.Id) + .SetOnInsert(p => p.VirtualMaschine, virtualMaschineId) + .SetOnInsert(p => p.UniqueId, config.Id) + .Set(p => p.Update, date) + .Set(p => p.Batch, batch) + + .Set(p => p.ParentId, config.ParentId) + .Set(p => p.Type, config.Type) + .Set(p => p.Name, config.Name) + .Set(p => p.Notes, notes) + .Set(p => p.CreationTime, config.CreationTime) + .Set(p => p.Generation, config.Generation) + .Set(p => p.Architecture, config.Architecture) + .Set(p => p.SecureBootEnabled, config.SecureBootEnabled) + .Set(p => p.IsAutomaticSnapshot, config.IsAutomaticSnapshot) + .Set(p => p.AutomaticStartupAction, config.AutomaticStartupAction?.ToString()) + .Set(p => p.AutomaticShutdownAction, config.AutomaticShutdownAction?.ToString()) + .Set(p => p.AutomaticRecoveryAction, config.AutomaticRecoveryAction?.ToString()) + .Set(p => p.AutomaticSnapshotsEnabled, config.AutomaticSnapshotsEnabled) + .Set(p => p.BaseBoardSerialNumber, config.BaseBoardSerialNumber) + .Set(p => p.BIOSSerialNumber, config.BIOSSerialNumber) + .Set(p => p.BIOSGUID, config.BIOSGUID) + .Set(p => p.ConfigurationDataRoot, config.ConfigurationDataRoot) + .Set(p => p.ConfigurationFile, config.ConfigurationFile) + .Set(p => p.GuestStateDataRoot, config.GuestStateDataRoot) + .Set(p => p.GuestStateFile, config.GuestStateFile) + .Set(p => p.SnapshotDataRoot, config.SnapshotDataRoot) + .Set(p => p.SuspendDataRoot, config.SuspendDataRoot) + .Set(p => p.SwapFileDataRoot, config.SwapFileDataRoot); + + configurationBulk.Add(new UpdateOneModel(configFilter, configUpdate) + { + IsUpsert = true + }); + } + } } + + configurationBulk.Add(new DeleteManyModel(Builders.Filter.And(new List> + { + Builders.Filter.Eq(x => x.Host, hostEntity.Id), + Builders.Filter.Ne(x => x.Batch, batch) + }))); + + var configurationResult = await _database.HostVirtualMaschineConfig().BulkWriteAsync(configurationBulk, cancellationToken: cancellationToken); } } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/Handlers/Web/ConsoleProxyHandler.cs b/src/Server/Insight.Server/Network/Handlers/Web/ConsoleProxyHandler.cs index 416ee10..4fa49f3 100644 --- a/src/Server/Insight.Server/Network/Handlers/Web/ConsoleProxyHandler.cs +++ b/src/Server/Insight.Server/Network/Handlers/Web/ConsoleProxyHandler.cs @@ -1,103 +1,103 @@ -using Insight.Agent.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; +using Insight.Domain.Messages.Web; using Insight.Infrastructure; using Insight.Infrastructure.Entities; -using Insight.Web.Interfaces; -using Insight.Web.Messages; using Microsoft.Extensions.Logging; using MongoDB.Driver; using Vaitr.Bus; using Vaitr.Network; -namespace Insight.Server.Network.Handlers.Web +namespace Insight.Server.Network.Handlers.Web; + +public class ConsoleProxyHandler : IMessageHandler { - public class ConsoleProxyHandler : IWebMessageHandler + private readonly List _subscriptions = new(); + + private readonly ISessionPool _agentPool; + private readonly ISessionPool _webPool; + private readonly IMongoDatabase _database; + private readonly Bus _bus; + private readonly ILogger _logger; + + public ConsoleProxyHandler( + ISessionPool agentPool, + ISessionPool webPool, + IMongoDatabase database, + Bus bus, + ILogger logger) { - private readonly List _subscriptions = new(); + _agentPool = agentPool; + _webPool = webPool; + _database = database; + _bus = bus; + _logger = logger; - private readonly ISessionPool _agentPool; - private readonly ISessionPool _webPool; - private readonly IMongoDatabase _database; - private readonly Bus _bus; - private readonly ILogger _logger; + _subscriptions.Add(_bus.SubscribeAsync(OnConsoleQueryAsync, null)); + } - public ConsoleProxyHandler( - ISessionPool agentPool, - ISessionPool webPool, - IMongoDatabase database, - Bus bus, - ILogger logger) + public async ValueTask HandleAsync(WebSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is ConsoleQueryProxyRequest consoleRequest) { - _agentPool = agentPool; - _webPool = webPool; - _database = database; - _bus = bus; - _logger = logger; - - _subscriptions.Add(_bus.SubscribeAsync(OnConsoleQueryAsync, null)); - } - - public async ValueTask HandleAsync(WebSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IWebMessage - { - if (message is ConsoleQueryProxyRequest consoleRequest) - { - await OnConsoleQueryRequestAsync(sender, consoleRequest, cancellationToken); - } - } - - private async ValueTask OnConsoleQueryRequestAsync(WebSession session, ConsoleQueryProxyRequest request, CancellationToken cancellationToken) - { - // get host - var hostEntity = await _database.Host() - .Find(Builders - .Filter - .Eq(p => p.Id, request.HostId)) - .FirstOrDefaultAsync(cancellationToken); - - if (hostEntity is null) - { - _logger.LogWarning("hostEntity is null"); - return; - } - - // get agent - var agentEntity = await _database.Agent() - .Find(Builders - .Filter - .Eq(p => p.Id, hostEntity.Agent)) - .FirstOrDefaultAsync(cancellationToken); - - if (agentEntity is null) - { - _logger.LogWarning("agentEntity is null"); - return; - } - - // check if agent online - if (_agentPool.FirstOrDefault(p => p.Value.Id == agentEntity.Id).Value is not AgentSession agent) return; - - // send "real" packet to agent - await agent.SendAsync(new ConsoleQueryRequest - { - Id = request.Id, - HostId = request.HostId, - Query = request.Query - }, cancellationToken); - } - - private async ValueTask OnConsoleQueryAsync(ConsoleQuery query, CancellationToken cancellationToken) - { - // check if web online - if (_webPool.FirstOrDefault().Value is not WebSession web) return; - - await web.SendAsync(new ConsoleQueryProxy - { - Id = query.Id, - HostId = query.HostId, - Query = query.Query, - Data = query.Data, - Errors = query.Errors, - HadErrors = query.HadErrors - }, cancellationToken); + await OnConsoleQueryRequestAsync(sender, consoleRequest, cancellationToken); } } + + private async ValueTask OnConsoleQueryRequestAsync(WebSession session, ConsoleQueryProxyRequest request, CancellationToken cancellationToken) + { + // get host + var hostEntity = await _database.Host() + .Find(Builders + .Filter + .Eq(p => p.Id, request.HostId)) + .FirstOrDefaultAsync(cancellationToken); + + if (hostEntity is null) + { + _logger.LogWarning("hostEntity is null"); + return; + } + + // get agent + var agentEntity = await _database.Agent() + .Find(Builders + .Filter + .Eq(p => p.Id, hostEntity.Agent)) + .FirstOrDefaultAsync(cancellationToken); + + if (agentEntity is null) + { + _logger.LogWarning("agentEntity is null"); + return; + } + + // check if agent online + if (_agentPool.FirstOrDefault(p => p.Value.Id == agentEntity.Id).Value is not AgentSession agent) return; + + // send "real" packet to agent + await agent.SendAsync(new ConsoleQueryRequest + { + Id = request.Id, + HostId = request.HostId, + Query = request.Query + }, cancellationToken); + } + + private async ValueTask OnConsoleQueryAsync(ConsoleQuery query, CancellationToken cancellationToken) + { + // check if web online + if (_webPool.FirstOrDefault().Value is not WebSession web) return; + + await web.SendAsync(new ConsoleQueryProxy + { + Id = query.Id, + HostId = query.HostId, + Query = query.Query, + Data = query.Data, + Errors = query.Errors, + HadErrors = query.HadErrors + }, cancellationToken); + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Network/WebSession.cs b/src/Server/Insight.Server/Network/WebSession.cs index 8c2e31c..df4d2c7 100644 --- a/src/Server/Insight.Server/Network/WebSession.cs +++ b/src/Server/Insight.Server/Network/WebSession.cs @@ -1,17 +1,17 @@ -using Insight.Web.Interfaces; -using Insight.Web.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; using Microsoft.Extensions.Logging; using Vaitr.Network; namespace Insight.Server.Network; -public class WebSession : TcpSession +public class WebSession : TcpSession { public string? Id { get; set; } - private readonly IEnumerable> _handlers; + private readonly IEnumerable> _handlers; - public WebSession(IEnumerable> handlers, ISerializer serializer, ILogger logger) : base(serializer, logger) + public WebSession(IEnumerable> handlers, ISerializer serializer, ILogger logger) : base(serializer, logger) { _handlers = handlers; } @@ -26,12 +26,12 @@ public class WebSession : TcpSession _logger.LogInformation("Web ({ep?}) disconnected", RemoteEndPoint); } - protected override async ValueTask OnSentAsync(IPacketContext context, CancellationToken cancellationToken) + protected override async ValueTask OnSentAsync(IPacketContext context, CancellationToken cancellationToken) { await base.OnSentAsync(context, cancellationToken); } - protected override async ValueTask OnReceivedAsync(IPacketContext context, CancellationToken cancellationToken) + protected override async ValueTask OnReceivedAsync(IPacketContext context, CancellationToken cancellationToken) { await base.OnReceivedAsync(context, cancellationToken); diff --git a/src/Server/Insight.Server/Program.cs b/src/Server/Insight.Server/Program.cs index 6a0659c..0000678 100644 --- a/src/Server/Insight.Server/Program.cs +++ b/src/Server/Insight.Server/Program.cs @@ -1,14 +1,12 @@ -using Insight.Agent.Interfaces; -using Insight.Agent.Messages; -using Insight.Domain.Constants; +using Insight.Domain.Constants; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; using Insight.Infrastructure; using Insight.Server.Extensions; using Insight.Server.Network; using Insight.Server.Network.Handlers.Agent; using Insight.Server.Network.Handlers.Web; using Insight.Server.Services; -using Insight.Web.Interfaces; -using Insight.Web.Messages; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -18,118 +16,117 @@ using Vaitr.Bus; using Vaitr.Network; using Vaitr.Network.Hosting; -namespace Insight.Server +namespace Insight.Server; + +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); + builder.UseWindowsService(); + builder.UseSystemd(); + + builder.ConfigureAppConfiguration(options => { - var builder = Host.CreateDefaultBuilder(args); - builder.UseWindowsService(); - builder.UseSystemd(); + options.Defaults(); + }); - builder.ConfigureAppConfiguration(options => + builder.ConfigureLogging(options => + { + options.ClearProviders(); + options.SetMinimumLevel(LogLevel.Trace); + + options.AddSimpleConsole(options => { - options.Defaults(); + options.IncludeScopes = true; + options.SingleLine = true; + options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff "; }); - builder.ConfigureLogging(options => + options.AddFile($"{Configuration.AppDirectory?.FullName}/" + "logs/server_{Date}.log", LogLevel.Trace, fileSizeLimitBytes: 104857600, retainedFileCountLimit: 10, outputTemplate: "{Timestamp:o} [{Level:u3}] {Message} {NewLine}{Exception}"); + }); + + builder.ConfigureServices((host, services) => + { + //var databaseLoggerFactory = LoggerFactory.Create(b => + //{ + // b.AddSimpleConsole(); + // b.SetMinimumLevel(LogLevel.Debug); + //}); + + // INFRASTRUCTURE + services.AddDatabase(host.Configuration); + + // AGENT SERVER + services.UseHostedServer(options => { - options.ClearProviders(); - options.SetMinimumLevel(LogLevel.Trace); + options.Address = IPAddress.Any; + options.Port = host.Configuration.GetValue(Appsettings.AgentServerPort) ?? throw new Exception($"{Appsettings.AgentServerPort} value not set (appsettings)"); + options.Keepalive = 10000; + options.Timeout = 30000; + options.Backlog = 128; - options.AddSimpleConsole(options => - { - options.IncludeScopes = true; - options.SingleLine = true; - options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff "; - }); + options.Encryption = Encryption.Tls12; + options.Certificate = host.Configuration.GetValue(Appsettings.AgentServerCertificate) ?? throw new Exception($"{Appsettings.AgentServerCertificate} value not set (appsettings)"); + options.CertificatePassword = host.Configuration.GetValue(Appsettings.AgentServerCertificatePassword) ?? throw new Exception($"{Appsettings.AgentServerCertificatePassword} value not set (appsettings)"); - options.AddFile($"{Configuration.AppDirectory?.FullName}/" + "logs/server_{Date}.log", LogLevel.Trace, fileSizeLimitBytes: 104857600, retainedFileCountLimit: 10, outputTemplate: "{Timestamp:o} [{Level:u3}] {Message} {NewLine}{Exception}"); + options.UseSerializer, IMessage>(); }); - builder.ConfigureServices((host, services) => + services.AddSingleton(); + services.AddSingleton, AgentHandler>(); + services.AddSingleton, DriveHandler>(); + services.AddSingleton, Network.Handlers.Agent.EventHandler>(); + services.AddSingleton, InterfaceHandler>(); + services.AddSingleton, MainboardHandler>(); + services.AddSingleton, MemoryHandler>(); + services.AddSingleton, OperationSystemHandler>(); + services.AddSingleton, PrinterHandler>(); + services.AddSingleton, ProcessorHandler>(); + services.AddSingleton, ServiceHandler>(); + services.AddSingleton, SessionHandler>(); + services.AddSingleton, SoftwareHandler>(); + services.AddSingleton, StoragePoolHandler>(); + services.AddSingleton, SystemInfoHandler>(); + services.AddSingleton, TrapHandler>(); + services.AddSingleton, UpdateHandler>(); + services.AddSingleton, UserHandler>(); + services.AddSingleton, VideocardHandler>(); + services.AddSingleton, VirtualMaschineHandler>(); + services.AddSingleton, ConsoleHandler>(); + + // WEB (FRONTEND-PROXY) SERVER + services.UseHostedServer(options => { - //var databaseLoggerFactory = LoggerFactory.Create(b => - //{ - // b.AddSimpleConsole(); - // b.SetMinimumLevel(LogLevel.Debug); - //}); + options.Address = IPAddress.Any; + options.Port = host.Configuration.GetValue(Appsettings.WebServerPort) ?? throw new Exception($"{Appsettings.WebServerPort} value not set (appsettings)"); + options.Keepalive = 10000; + options.Timeout = 30000; + options.Backlog = 128; - // INFRASTRUCTURE - services.AddDatabase(host.Configuration); + options.Encryption = Encryption.Tls12; + options.Certificate = host.Configuration.GetValue(Appsettings.WebServerCertificate) ?? throw new Exception($"{Appsettings.WebServerCertificate} value not set (appsettings)"); + options.CertificatePassword = host.Configuration.GetValue(Appsettings.WebServerCertificatePassword) ?? throw new Exception($"{Appsettings.WebServerCertificatePassword} value not set (appsettings)"); - // AGENT SERVER - services.UseHostedServer(options => - { - options.Address = IPAddress.Any; - options.Port = host.Configuration.GetValue(Appsettings.AgentServerPort) ?? throw new Exception($"{Appsettings.AgentServerPort} value not set (appsettings)"); - options.Keepalive = 10000; - options.Timeout = 30000; - options.Backlog = 128; - - options.Encryption = Encryption.Tls12; - options.Certificate = host.Configuration.GetValue(Appsettings.AgentServerCertificate) ?? throw new Exception($"{Appsettings.AgentServerCertificate} value not set (appsettings)"); - options.CertificatePassword = host.Configuration.GetValue(Appsettings.AgentServerCertificatePassword) ?? throw new Exception($"{Appsettings.AgentServerCertificatePassword} value not set (appsettings)"); - - options.UseSerializer, IAgentMessage>(); - }); - - services.AddSingleton(); - services.AddSingleton, AgentHandler>(); - services.AddSingleton, DriveHandler>(); - services.AddSingleton, Network.Handlers.Agent.EventHandler>(); - services.AddSingleton, InterfaceHandler>(); - services.AddSingleton, MainboardHandler>(); - services.AddSingleton, MemoryHandler>(); - services.AddSingleton, OperationSystemHandler>(); - services.AddSingleton, PrinterHandler>(); - services.AddSingleton, ProcessorHandler>(); - services.AddSingleton, ServiceHandler>(); - services.AddSingleton, SessionHandler>(); - services.AddSingleton, SoftwareHandler>(); - services.AddSingleton, StoragePoolHandler>(); - services.AddSingleton, SystemInfoHandler>(); - services.AddSingleton, TrapHandler>(); - services.AddSingleton, UpdateHandler>(); - services.AddSingleton, UserHandler>(); - services.AddSingleton, VideocardHandler>(); - services.AddSingleton, VirtualMaschineHandler>(); - services.AddSingleton, ConsoleHandler>(); - - // WEB (FRONTEND-PROXY) SERVER - services.UseHostedServer(options => - { - options.Address = IPAddress.Any; - options.Port = host.Configuration.GetValue(Appsettings.WebServerPort) ?? throw new Exception($"{Appsettings.WebServerPort} value not set (appsettings)"); - options.Keepalive = 10000; - options.Timeout = 30000; - options.Backlog = 128; - - options.Encryption = Encryption.Tls12; - options.Certificate = host.Configuration.GetValue(Appsettings.WebServerCertificate) ?? throw new Exception($"{Appsettings.WebServerCertificate} value not set (appsettings)"); - options.CertificatePassword = host.Configuration.GetValue(Appsettings.WebServerCertificatePassword) ?? throw new Exception($"{Appsettings.WebServerCertificatePassword} value not set (appsettings)"); - - options.UseSerializer, IWebMessage>(); - }); - - services.AddSingleton, ConsoleProxyHandler>(); - - // DISPATCH - services.AddHostedService(); - services.AddHostedService(); - - // GLOBAL DEPENDENCIES - services.AddSingleton(); - services.AddTransient(provider => new HttpClient(new HttpClientHandler - { - ClientCertificateOptions = ClientCertificateOption.Manual, - ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => true - })); + options.UseSerializer, IMessage>(); }); - var host = builder.Build(); - await host.RunAsync().ConfigureAwait(false); - } + services.AddSingleton, ConsoleProxyHandler>(); + + // DISPATCH + services.AddHostedService(); + services.AddHostedService(); + + // GLOBAL DEPENDENCIES + services.AddSingleton(); + services.AddTransient(provider => new HttpClient(new HttpClientHandler + { + ClientCertificateOptions = ClientCertificateOption.Manual, + ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => true + })); + }); + + var host = builder.Build(); + await host.RunAsync().ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Services/DispatchService.cs b/src/Server/Insight.Server/Services/DispatchService.cs index 7d3b6c4..23b7a25 100644 --- a/src/Server/Insight.Server/Services/DispatchService.cs +++ b/src/Server/Insight.Server/Services/DispatchService.cs @@ -1,4 +1,4 @@ -using Insight.Agent.Enums; +using Insight.Domain.Enums; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using Microsoft.Extensions.Configuration; @@ -6,153 +6,152 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using MongoDB.Driver; -namespace Insight.Server.Services +namespace Insight.Server.Services; + +internal class DispatchService : BackgroundService { - internal class DispatchService : BackgroundService + private readonly HttpClient _httpClient; + private readonly IMongoDatabase _database; + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + + public DispatchService(HttpClient httpClient, IMongoDatabase database, IConfiguration configuration, ILogger logger) { - private readonly HttpClient _httpClient; - private readonly IMongoDatabase _database; - private readonly IConfiguration _configuration; - private readonly ILogger _logger; + _httpClient = httpClient; + _database = database; + _configuration = configuration; + _logger = logger; + } - public DispatchService(HttpClient httpClient, IMongoDatabase database, IConfiguration configuration, ILogger logger) + protected override async Task ExecuteAsync(CancellationToken cancellationToken) + { + _logger.LogTrace("ExecuteAsync"); + + var enabled = _configuration.GetValue(Appsettings.DispatchWebmatic) ?? throw new Exception($"{Appsettings.DispatchWebmatic} value not set (appsettings)"); + if (enabled is false) return; + + try { - _httpClient = httpClient; - _database = database; - _configuration = configuration; - _logger = logger; + while (cancellationToken.IsCancellationRequested is false) + { + await DispatchAsync(cancellationToken); + await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); + } } + catch (OperationCanceledException) { } + catch (Exception) { } + } - protected override async Task ExecuteAsync(CancellationToken cancellationToken) + private async ValueTask DispatchAsync(CancellationToken cancellationToken) + { + _logger.LogTrace($"DispatchAsync"); + + var pendings = await _database.HostLogMonitoring() + .Find(Builders + .Filter.Eq(p => p.Dispatch, DispatchEnum.Pending.ToString())) + .Limit(10) + .ToListAsync(cancellationToken); + + if (pendings is null || pendings.Any() is false) return; + + foreach (var entity in pendings) { - _logger.LogTrace("ExecuteAsync"); - - var enabled = _configuration.GetValue(Appsettings.DispatchWebmatic) ?? throw new Exception($"{Appsettings.DispatchWebmatic} value not set (appsettings)"); - if (enabled is false) return; - try { - while (cancellationToken.IsCancellationRequested is false) - { - await DispatchAsync(cancellationToken); - await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); - } + var result = await SendAsync(entity, default); + + await _database.HostLogMonitoring() + .UpdateOneAsync(Builders.Filter + .Eq(p => p.Id, entity.Id), Builders + .Update + .Set(p => p.Dispatch, result.ToString()), cancellationToken: default); } - catch (OperationCanceledException) { } - catch (Exception) { } - } - - private async ValueTask DispatchAsync(CancellationToken cancellationToken) - { - _logger.LogTrace($"DispatchAsync"); - - var pendings = await _database.HostLogMonitoring() - .Find(Builders - .Filter.Eq(p => p.Dispatch, DispatchEnum.Pending.ToString())) - .Limit(10) - .ToListAsync(cancellationToken); - - if (pendings is null || pendings.Any() is false) return; - - foreach (var entity in pendings) + catch (Exception ex) { - try - { - var result = await SendAsync(entity, default); - - await _database.HostLogMonitoring() - .UpdateOneAsync(Builders.Filter - .Eq(p => p.Id, entity.Id), Builders - .Update - .Set(p => p.Dispatch, result.ToString()), cancellationToken: default); - } - catch (Exception ex) - { - _logger.LogError(ex.Message); - _logger.LogTrace(ex.StackTrace); - } - finally - { - // webmatic safety offset - await Task.Delay(TimeSpan.FromSeconds(1), default); - } + _logger.LogError(ex.Message); + _logger.LogTrace(ex.StackTrace); } - } - - private async ValueTask SendAsync(HostLogMonitoringEntity monitoring, CancellationToken cancellationToken) - { - _logger.LogTrace($"SendAsync ({monitoring})"); - - var monitoringApi = Monitoring.LogUri; - var monitoringContent = new List>(); - var monitoringResult = new List>(); - - // adjust by category - if (Enum.TryParse(monitoring.Category, true, out var monitoringCategory) is false) return DispatchEnum.Failure; - - if (monitoringCategory == CategoryEnum.Monitoring) monitoringApi = Monitoring.StatusUri; - - // set category (if log) - if (monitoringApi == Monitoring.LogUri) monitoringContent.Add(new KeyValuePair("category", monitoringCategory.ToString())); - - // host resolve - var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Id, monitoring.Host?.ToString())).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return DispatchEnum.Failure; - - // customer resolve - var customerEntity = await _database.Customer().Find(Builders.Filter.Eq(p => p.Id, hostEntity.Customer)).FirstOrDefaultAsync(cancellationToken); - if (hostEntity is null) return DispatchEnum.Failure; - - // set host name if no remote host set - if (string.IsNullOrEmpty(monitoring.Hostname)) monitoring.Hostname = hostEntity.Name; - - // remove any domain from hostname - if (monitoring.Hostname is not null && monitoring.Hostname.Contains('.')) monitoring.Hostname = monitoring.Hostname.Split(".")[0]; - - // add customer tag to hostname - monitoring.Hostname += $".{customerEntity.Tag}"; - - // if task null, set hostname - if (string.IsNullOrEmpty(monitoring.Task)) monitoring.Task = monitoring.Hostname; - - // insert hostname as computer-name (lowercase) - monitoringContent.Add(new KeyValuePair("computer_name", monitoring.Hostname.ToLower())); - - // insert converted status (api styled) - if (Enum.TryParse(monitoring.Status, true, out var monitoringStatus) is false) return DispatchEnum.Failure; - - monitoringContent.Add(monitoringStatus switch + finally { - StatusEnum.Information => new KeyValuePair("status", monitoringApi == Monitoring.StatusUri ? "erfolgreich" : "info"), - StatusEnum.Warning => new KeyValuePair("status", monitoringApi == Monitoring.StatusUri ? "Interaktion" : "warning"), - StatusEnum.Error => new KeyValuePair("status", monitoringApi == Monitoring.StatusUri ? "fehlgeschlagen" : "error"), - _ => throw new NotImplementedException(nameof(monitoringStatus)) - }); - - // insert task, timestamp, message, - monitoringContent.Add(new KeyValuePair("task", monitoring.Task)); - - if (monitoring.Timestamp is not null) - { - monitoringContent.Add(new KeyValuePair("timestamp", monitoring.Timestamp.Value.ToLocalTime().ToString())); + // webmatic safety offset + await Task.Delay(TimeSpan.FromSeconds(1), default); } - - if (string.IsNullOrWhiteSpace(monitoring.Message) is false) - { - monitoringContent.Add(new KeyValuePair("message", monitoring.Message)); - } - - // send message - var result = await _httpClient.PostAsync(monitoringApi, new FormUrlEncodedContent(monitoringContent), default); - - monitoringResult.Add(new KeyValuePair("HttpStatusCode", result.StatusCode.ToString())); - monitoringResult.Add(new KeyValuePair("HttpResponseMessage", await result.Content.ReadAsStringAsync(default))); - - // if content != "OK" - if (result is null || result.IsSuccessStatusCode == false) return DispatchEnum.Failure; - - // success - return DispatchEnum.Success; } } + + private async ValueTask SendAsync(HostLogMonitoringEntity monitoring, CancellationToken cancellationToken) + { + _logger.LogTrace($"SendAsync ({monitoring})"); + + var monitoringApi = Monitoring.LogUri; + var monitoringContent = new List>(); + var monitoringResult = new List>(); + + // adjust by category + if (Enum.TryParse(monitoring.Category, true, out var monitoringCategory) is false) return DispatchEnum.Failure; + + if (monitoringCategory == CategoryEnum.Monitoring) monitoringApi = Monitoring.StatusUri; + + // set category (if log) + if (monitoringApi == Monitoring.LogUri) monitoringContent.Add(new KeyValuePair("category", monitoringCategory.ToString())); + + // host resolve + var hostEntity = await _database.Host().Find(Builders.Filter.Eq(p => p.Id, monitoring.Host?.ToString())).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return DispatchEnum.Failure; + + // customer resolve + var customerEntity = await _database.Customer().Find(Builders.Filter.Eq(p => p.Id, hostEntity.Customer)).FirstOrDefaultAsync(cancellationToken); + if (hostEntity is null) return DispatchEnum.Failure; + + // set host name if no remote host set + if (string.IsNullOrEmpty(monitoring.Hostname)) monitoring.Hostname = hostEntity.Name; + + // remove any domain from hostname + if (monitoring.Hostname is not null && monitoring.Hostname.Contains('.')) monitoring.Hostname = monitoring.Hostname.Split(".")[0]; + + // add customer tag to hostname + monitoring.Hostname += $".{customerEntity.Tag}"; + + // if task null, set hostname + if (string.IsNullOrEmpty(monitoring.Task)) monitoring.Task = monitoring.Hostname; + + // insert hostname as computer-name (lowercase) + monitoringContent.Add(new KeyValuePair("computer_name", monitoring.Hostname.ToLower())); + + // insert converted status (api styled) + if (Enum.TryParse(monitoring.Status, true, out var monitoringStatus) is false) return DispatchEnum.Failure; + + monitoringContent.Add(monitoringStatus switch + { + StatusEnum.Information => new KeyValuePair("status", monitoringApi == Monitoring.StatusUri ? "erfolgreich" : "info"), + StatusEnum.Warning => new KeyValuePair("status", monitoringApi == Monitoring.StatusUri ? "Interaktion" : "warning"), + StatusEnum.Error => new KeyValuePair("status", monitoringApi == Monitoring.StatusUri ? "fehlgeschlagen" : "error"), + _ => throw new NotImplementedException(nameof(monitoringStatus)) + }); + + // insert task, timestamp, message, + monitoringContent.Add(new KeyValuePair("task", monitoring.Task)); + + if (monitoring.Timestamp is not null) + { + monitoringContent.Add(new KeyValuePair("timestamp", monitoring.Timestamp.Value.ToLocalTime().ToString())); + } + + if (string.IsNullOrWhiteSpace(monitoring.Message) is false) + { + monitoringContent.Add(new KeyValuePair("message", monitoring.Message)); + } + + // send message + var result = await _httpClient.PostAsync(monitoringApi, new FormUrlEncodedContent(monitoringContent), default); + + monitoringResult.Add(new KeyValuePair("HttpStatusCode", result.StatusCode.ToString())); + monitoringResult.Add(new KeyValuePair("HttpResponseMessage", await result.Content.ReadAsStringAsync(default))); + + // if content != "OK" + if (result is null || result.IsSuccessStatusCode == false) return DispatchEnum.Failure; + + // success + return DispatchEnum.Success; + } } \ No newline at end of file diff --git a/src/Server/Insight.Server/Services/JobService.cs b/src/Server/Insight.Server/Services/JobService.cs index 3e800a3..cb8b619 100644 --- a/src/Server/Insight.Server/Services/JobService.cs +++ b/src/Server/Insight.Server/Services/JobService.cs @@ -1,4 +1,5 @@ -using Insight.Agent.Messages; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Agent; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using Insight.Server.Extensions; @@ -8,72 +9,71 @@ using Microsoft.Extensions.Logging; using MongoDB.Driver; using Vaitr.Network; -namespace Insight.Server.Services +namespace Insight.Server.Services; + +internal class JobService : BackgroundService { - internal class JobService : BackgroundService + private readonly ISessionPool _agentPool; + private readonly IMongoDatabase _database; + private readonly ILogger _logger; + + public JobService(ISessionPool agentPool, IMongoDatabase database, ILogger logger) { - private readonly ISessionPool _agentPool; - private readonly IMongoDatabase _database; - private readonly ILogger _logger; + _agentPool = agentPool; + _database = database; + _logger = logger; + } - public JobService(ISessionPool agentPool, IMongoDatabase database, ILogger logger) + protected override async Task ExecuteAsync(CancellationToken cancellationToken) + { + _logger.LogTrace("ExecuteAsync"); + + var jobs = new List { - _agentPool = agentPool; - _database = database; - _logger = logger; - } - - protected override async Task ExecuteAsync(CancellationToken cancellationToken) - { - _logger.LogTrace("ExecuteAsync"); - - var jobs = new List + Task.Run(async () => { - Task.Run(async () => + while (cancellationToken.IsCancellationRequested is false) { - while (cancellationToken.IsCancellationRequested is false) + try { - try + foreach (var agent in await GetAssignedAgentsAsync(cancellationToken)) { - foreach (var agent in await GetAssignedAgentsAsync(cancellationToken)) - { - await agent.SendAsync(new GetInventory(), cancellationToken); - } - } - catch (OperationCanceledException) { } - catch (Exception) { } - finally - { - await Task.Delay(TimeSpan.FromHours(1), cancellationToken); + await agent.SendAsync(new InventoryRequest(), cancellationToken); } } - }, default) - }; + catch (OperationCanceledException) { } + catch (Exception) { } + finally + { + await Task.Delay(TimeSpan.FromHours(1), cancellationToken); + } + } + }, default) + }; - try - { - await Task.WhenAll(jobs).ConfigureAwait(false); - } - catch (OperationCanceledException) { } - catch (Exception) { } - } - - private async ValueTask> GetAssignedAgentsAsync(CancellationToken cancellationToken) + try { - var valid = new List(); - - await Async.ParallelForEach(_agentPool.Where(p => p.Value.Id is not null), async x => - { - var host = await _database.Host() - .Find(Builders.Filter.Eq(p => p.Agent, x.Value.Id)) - .FirstOrDefaultAsync(cancellationToken) - .ConfigureAwait(false); - - if (host is null) return; - valid.Add(x.Value); - }); - - return valid; + await Task.WhenAll(jobs).ConfigureAwait(false); } + catch (OperationCanceledException) { } + catch (Exception) { } + } + + private async ValueTask> GetAssignedAgentsAsync(CancellationToken cancellationToken) + { + var valid = new List(); + + await Async.ParallelForEach(_agentPool.Where(p => p.Value.Id is not null), async x => + { + var host = await _database.Host() + .Find(Builders.Filter.Eq(p => p.Agent, x.Value.Id)) + .FirstOrDefaultAsync(cancellationToken) + .ConfigureAwait(false); + + if (host is null) return; + valid.Add(x.Value); + }); + + return valid; } } \ No newline at end of file diff --git a/src/Setup/Insight.Setup.Windows/Insight.Setup.Windows.csproj b/src/Setup/Insight.Setup.Windows/Insight.Setup.Windows.csproj index 92fa03c..5437db6 100644 --- a/src/Setup/Insight.Setup.Windows/Insight.Setup.Windows.csproj +++ b/src/Setup/Insight.Setup.Windows/Insight.Setup.Windows.csproj @@ -8,7 +8,7 @@ setup Insight.Setup Insight - 2023.7.3.0 + 2023.9.21.1 diff --git a/src/Updater/Insight.Updater/Insight.Updater.csproj b/src/Updater/Insight.Updater/Insight.Updater.csproj index 3e39aee..d277e80 100644 --- a/src/Updater/Insight.Updater/Insight.Updater.csproj +++ b/src/Updater/Insight.Updater/Insight.Updater.csproj @@ -6,7 +6,7 @@ Insight Insight.Updater updater - 2023.7.3.0 + 2023.9.21.1 enable enable diff --git a/src/Web/Insight.Web.Assets/Insight.Web.Assets.csproj b/src/Web/Insight.Web.Assets/Insight.Web.Assets.csproj deleted file mode 100644 index 64f79ee..0000000 --- a/src/Web/Insight.Web.Assets/Insight.Web.Assets.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - net7.0 - true - enable - Insight.Web.Assets - Insight.Web - Insight - 2023.9.14.0 - - - - - - - - diff --git a/src/Web/Insight.Web.Assets/Interfaces/IWebMessageHandler.cs b/src/Web/Insight.Web.Assets/Interfaces/IWebMessageHandler.cs deleted file mode 100644 index 2609347..0000000 --- a/src/Web/Insight.Web.Assets/Interfaces/IWebMessageHandler.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Insight.Web.Messages; - -namespace Insight.Web.Interfaces -{ - public partial interface IWebMessageHandler - { - ValueTask HandleAsync(TSender sender, TMessage message, CancellationToken cancellationToken) where TMessage : IWebMessage; - } -} \ No newline at end of file diff --git a/src/Web/Insight.Web.Assets/Messages/Host/ConsoleProxy.cs b/src/Web/Insight.Web.Assets/Messages/Host/ConsoleProxy.cs deleted file mode 100644 index 0a5783f..0000000 --- a/src/Web/Insight.Web.Assets/Messages/Host/ConsoleProxy.cs +++ /dev/null @@ -1,43 +0,0 @@ -using MemoryPack; - -namespace Insight.Web.Messages -{ - [MemoryPackUnion(1, typeof(ConsoleQueryProxy))] - [MemoryPackUnion(2, typeof(ConsoleQueryProxyRequest))] - public partial interface IWebMessage { } - - [MemoryPackable] - public partial class ConsoleQueryProxy : IWebMessage - { - [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(7)] - public bool HadErrors { get; set; } - } - - [MemoryPackable] - public partial class ConsoleQueryProxyRequest : IWebMessage - { - [MemoryPackOrder(0)] - public string? Id { get; set; } - - [MemoryPackOrder(1)] - public string? HostId { get; set; } - - [MemoryPackOrder(2)] - public string? Query { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Insight.Web.Assets/Messages/IWebMessage.cs b/src/Web/Insight.Web.Assets/Messages/IWebMessage.cs deleted file mode 100644 index 6ac0a66..0000000 --- a/src/Web/Insight.Web.Assets/Messages/IWebMessage.cs +++ /dev/null @@ -1,7 +0,0 @@ -using MemoryPack; - -namespace Insight.Web.Messages -{ - [MemoryPackable] - public partial interface IWebMessage { } -} \ No newline at end of file diff --git a/src/Web/Insight.Web/Constants/Navigation.cs b/src/Web/Insight.Web/Constants/Navigation.cs index aadb16b..8f10442 100644 --- a/src/Web/Insight.Web/Constants/Navigation.cs +++ b/src/Web/Insight.Web/Constants/Navigation.cs @@ -20,7 +20,7 @@ public static class Navigation public const string Logout = "account/logout"; public const string Lockout = "account/lockout"; public const string Profile = "account/profile"; - public const string ChangePassword = "account/changepassword"; + public const string ChangePassword = "account/changepassword"; public static string LoginHref(string redirect) { @@ -106,7 +106,7 @@ public static class Navigation { public const string Index = "management/accounts"; public const string Details = "management/accounts/{accountId}"; - + public static string DetailsHref(string? accountId) { return Details.Replace("{accountId}", accountId); diff --git a/src/Web/Insight.Web/Insight.Web.csproj b/src/Web/Insight.Web/Insight.Web.csproj index a8871a1..827c2fb 100644 --- a/src/Web/Insight.Web/Insight.Web.csproj +++ b/src/Web/Insight.Web/Insight.Web.csproj @@ -4,7 +4,7 @@ net7.0 Insight web - 2023.9.18.0 + 2023.9.21.1 Insight.Web enable enable @@ -42,9 +42,7 @@ - - diff --git a/src/Web/Insight.Web/Models/Account/LoginModel.cs b/src/Web/Insight.Web/Models/Account/LoginModel.cs index aed6f6c..89e18f0 100644 --- a/src/Web/Insight.Web/Models/Account/LoginModel.cs +++ b/src/Web/Insight.Web/Models/Account/LoginModel.cs @@ -1,6 +1,4 @@ -using System.ComponentModel.DataAnnotations; - -namespace Insight.Web.Models.Account; +namespace Insight.Web.Models.Account; public class LoginModel { diff --git a/src/Web/Insight.Web/Network/Handlers/ConsoleHandler.cs b/src/Web/Insight.Web/Network/Handlers/ConsoleHandler.cs index 6e87b6d..0fc7b16 100644 --- a/src/Web/Insight.Web/Network/Handlers/ConsoleHandler.cs +++ b/src/Web/Insight.Web/Network/Handlers/ConsoleHandler.cs @@ -1,24 +1,24 @@ -using Insight.Web.Interfaces; -using Insight.Web.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Web; using Vaitr.Bus; -namespace Insight.Web.Network.Handlers +namespace Insight.Web.Network.Handlers; + +public class ConsoleHandler : IMessageHandler { - public class ConsoleHandler : IWebMessageHandler + private readonly Bus _bus; + + public ConsoleHandler(Bus bus) { - private readonly Bus _bus; + _bus = bus; + } - public ConsoleHandler(Bus bus) + public async ValueTask HandleAsync(WebSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage + { + if (message is ConsoleQueryProxy consoleQuery) { - _bus = bus; - } - - public async ValueTask HandleAsync(WebSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IWebMessage - { - if (message is ConsoleQueryProxy consoleQuery) - { - await _bus.PublishAsync(consoleQuery, cancellationToken); - } + await _bus.PublishAsync(consoleQuery, cancellationToken); } } } \ No newline at end of file diff --git a/src/Web/Insight.Web/Network/WebSession.cs b/src/Web/Insight.Web/Network/WebSession.cs index e3e16d4..8dbd7ff 100644 --- a/src/Web/Insight.Web/Network/WebSession.cs +++ b/src/Web/Insight.Web/Network/WebSession.cs @@ -1,56 +1,55 @@ -using Insight.Web.Interfaces; -using Insight.Web.Messages; +using Insight.Domain.Interfaces; +using Insight.Domain.Messages; using Vaitr.Network; -namespace Insight.Web.Network +namespace Insight.Web.Network; + +public class WebSession : TcpSession { - public class WebSession : TcpSession + private readonly IEnumerable> _handlers; + + public WebSession(IEnumerable> handlers, ISerializer serializer, ILogger logger) : base(serializer, logger) { - private readonly IEnumerable> _handlers; + _handlers = handlers; + } - public WebSession(IEnumerable> handlers, ISerializer serializer, ILogger logger) : base(serializer, logger) + protected override ValueTask OnConnectedAsync(CancellationToken cancellationToken) + { + _logger.LogInformation("Web ({ep?}) connected", RemoteEndPoint); + return default; + } + + protected override ValueTask OnDisconnectedAsync(CancellationToken cancellationToken) + { + _logger.LogInformation("Web ({ep?}) disconnected", RemoteEndPoint); + return default; + } + + protected override ValueTask OnSentAsync(IPacketContext context, CancellationToken cancellationToken) + { + return base.OnSentAsync(context, cancellationToken); + } + + protected override async ValueTask OnReceivedAsync(IPacketContext context, CancellationToken cancellationToken) + { + await base.OnReceivedAsync(context, cancellationToken); + + foreach (var handler in _handlers) { - _handlers = handlers; - } - - protected override ValueTask OnConnectedAsync(CancellationToken cancellationToken) - { - _logger.LogInformation("Web ({ep?}) connected", RemoteEndPoint); - return default; - } - - protected override ValueTask OnDisconnectedAsync(CancellationToken cancellationToken) - { - _logger.LogInformation("Web ({ep?}) disconnected", RemoteEndPoint); - return default; - } - - protected override ValueTask OnSentAsync(IPacketContext context, CancellationToken cancellationToken) - { - return base.OnSentAsync(context, cancellationToken); - } - - protected override async ValueTask OnReceivedAsync(IPacketContext context, CancellationToken cancellationToken) - { - await base.OnReceivedAsync(context, cancellationToken); - - foreach (var handler in _handlers) + try { - try - { - await handler.HandleAsync(this, context.Packet, cancellationToken); - } - catch (Exception ex) - { - _logger.LogWarning("Web ({ep?}) {ex}", RemoteEndPoint, ex.ToString()); - } + await handler.HandleAsync(this, context.Packet, cancellationToken); + } + catch (Exception ex) + { + _logger.LogWarning("Web ({ep?}) {ex}", RemoteEndPoint, ex.ToString()); } } + } - protected override ValueTask OnHeartbeatAsync(CancellationToken cancellationToken) - { - _logger.LogInformation("Web ({ep?}) Heartbeat", RemoteEndPoint); - return default; - } + protected override ValueTask OnHeartbeatAsync(CancellationToken cancellationToken) + { + _logger.LogInformation("Web ({ep?}) Heartbeat", RemoteEndPoint); + return default; } } \ No newline at end of file diff --git a/src/Web/Insight.Web/Pages/Inventory/Systems/StoragePools/Index.razor b/src/Web/Insight.Web/Pages/Inventory/Systems/StoragePools/Index.razor index 8e0c47d..9a25827 100644 --- a/src/Web/Insight.Web/Pages/Inventory/Systems/StoragePools/Index.razor +++ b/src/Web/Insight.Web/Pages/Inventory/Systems/StoragePools/Index.razor @@ -1,4 +1,4 @@ -@using static Insight.Agent.Messages.StoragePool; +@using static Insight.Domain.Messages.Agent.StoragePool; @inherits ComponentBase (context.Status, true) switch + color = Enum.Parse(context.Status, true) switch { - Insight.Agent.Enums.StatusEnum.Information => Color.Success, - Insight.Agent.Enums.StatusEnum.Warning => Color.Warning, - Insight.Agent.Enums.StatusEnum.Error => Color.Error, + Insight.Domain.Enums.StatusEnum.Information => Color.Success, + Insight.Domain.Enums.StatusEnum.Warning => Color.Warning, + Insight.Domain.Enums.StatusEnum.Error => Color.Error, _ => Color.Inherit }; } diff --git a/src/Web/Insight.Web/Pages/Management/Agents/Logs.razor.cs b/src/Web/Insight.Web/Pages/Management/Agents/Logs.razor.cs index 7a56ffc..412cff4 100644 --- a/src/Web/Insight.Web/Pages/Management/Agents/Logs.razor.cs +++ b/src/Web/Insight.Web/Pages/Management/Agents/Logs.razor.cs @@ -1,4 +1,4 @@ -using Insight.Agent.Enums; +using Insight.Domain.Enums; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using Insight.Web.Components.Containers; diff --git a/src/Web/Insight.Web/Pages/Management/Hosts/Actions/Console/Index.razor.cs b/src/Web/Insight.Web/Pages/Management/Hosts/Actions/Console/Index.razor.cs index fd6b36d..535c28b 100644 --- a/src/Web/Insight.Web/Pages/Management/Hosts/Actions/Console/Index.razor.cs +++ b/src/Web/Insight.Web/Pages/Management/Hosts/Actions/Console/Index.razor.cs @@ -1,7 +1,8 @@ -using Insight.Infrastructure; +using Insight.Domain.Messages; +using Insight.Domain.Messages.Web; +using Insight.Infrastructure; using Insight.Infrastructure.Entities; using Insight.Web.Constants; -using Insight.Web.Messages; using Insight.Web.Network; using Microsoft.AspNetCore.Components; using MongoDB.Bson; @@ -17,7 +18,7 @@ public partial class Index { [Parameter] public string? HostId { get; set; } - [Inject] private ISessionPool WebPool { get; init; } = default!; + [Inject] private ISessionPool WebPool { get; init; } = default!; [Inject] private IMongoDatabase Database { get; init; } = default!; [Inject] private ISnackbar Snackbar { get; init; } = default!; [Inject] private Bus Bus { get; init; } = default!; diff --git a/src/Web/Insight.Web/Pages/Management/Hosts/Logs.razor b/src/Web/Insight.Web/Pages/Management/Hosts/Logs.razor index c8fd3ce..d835ae8 100644 --- a/src/Web/Insight.Web/Pages/Management/Hosts/Logs.razor +++ b/src/Web/Insight.Web/Pages/Management/Hosts/Logs.razor @@ -1,5 +1,5 @@ @inherits ComponentBase -@using Insight.Agent.Enums; +@using Insight.Domain.Enums; (context.Status, true) switch + color = Enum.Parse(context.Status, true) switch { - Insight.Agent.Enums.StatusEnum.Information => Color.Success, - Insight.Agent.Enums.StatusEnum.Warning => Color.Warning, - Insight.Agent.Enums.StatusEnum.Error => Color.Error, + Insight.Domain.Enums.StatusEnum.Information => Color.Success, + Insight.Domain.Enums.StatusEnum.Warning => Color.Warning, + Insight.Domain.Enums.StatusEnum.Error => Color.Error, _ => Color.Inherit }; } diff --git a/src/Web/Insight.Web/Pages/Management/Hosts/Logs.razor.cs b/src/Web/Insight.Web/Pages/Management/Hosts/Logs.razor.cs index 2dd074e..0538514 100644 --- a/src/Web/Insight.Web/Pages/Management/Hosts/Logs.razor.cs +++ b/src/Web/Insight.Web/Pages/Management/Hosts/Logs.razor.cs @@ -1,4 +1,4 @@ -using Insight.Agent.Enums; +using Insight.Domain.Enums; using Insight.Infrastructure; using Insight.Infrastructure.Entities; using Insight.Web.Components.Containers; diff --git a/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/Details.razor b/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/Details.razor index d271380..d7c1e28 100644 --- a/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/Details.razor +++ b/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/Details.razor @@ -1,4 +1,4 @@ -@using static Insight.Agent.Messages.StoragePool; +@using static Insight.Domain.Messages.Agent.StoragePool; @inherits ComponentBase diff --git a/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/Index.razor b/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/Index.razor index fad8ab2..9947582 100644 --- a/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/Index.razor +++ b/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/Index.razor @@ -1,4 +1,4 @@ -@using static Insight.Agent.Messages.StoragePool; +@using static Insight.Domain.Messages.Agent.StoragePool; @inherits ComponentBase diff --git a/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/PhysicalDisks/Index.razor b/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/PhysicalDisks/Index.razor index f34a46c..6b3e104 100644 --- a/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/PhysicalDisks/Index.razor +++ b/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/PhysicalDisks/Index.razor @@ -1,4 +1,4 @@ -@using static Insight.Agent.Messages.PhysicalDisk; +@using static Insight.Domain.Messages.Agent.PhysicalDisk; @inherits ComponentBase diff --git a/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/VirtualDisks/Index.razor b/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/VirtualDisks/Index.razor index 0799f74..7eb4d6b 100644 --- a/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/VirtualDisks/Index.razor +++ b/src/Web/Insight.Web/Pages/Management/Hosts/Systems/StoragePools/VirtualDisks/Index.razor @@ -1,4 +1,4 @@ -@using static Insight.Agent.Messages.VirtualDisk; +@using static Insight.Domain.Messages.Agent.VirtualDisk; @inherits ComponentBase diff --git a/src/Web/Insight.Web/Pages/Management/Hosts/Systems/VirtualMaschines/Index.razor b/src/Web/Insight.Web/Pages/Management/Hosts/Systems/VirtualMaschines/Index.razor index 3b0b99a..51a734c 100644 --- a/src/Web/Insight.Web/Pages/Management/Hosts/Systems/VirtualMaschines/Index.razor +++ b/src/Web/Insight.Web/Pages/Management/Hosts/Systems/VirtualMaschines/Index.razor @@ -1,4 +1,4 @@ -@using static Insight.Agent.Messages.VirtualMaschine; +@using static Insight.Domain.Messages.Agent.VirtualMaschine; @inherits ComponentBase (options => + builder.Services.UseHostedClient(options => { options.Host = builder.Configuration.GetValue(Appsettings.ServerHost) ?? throw new Exception($"{Appsettings.ServerHost} value not set (appsettings)"); options.Port = builder.Configuration.GetValue(Appsettings.ServerPort) ?? throw new Exception($"{Appsettings.ServerPort} value not set (appsettings)"); @@ -68,10 +68,10 @@ public class Program options.Timeout = 30000; options.Encryption = Encryption.Tls12; - options.UseSerializer, IWebMessage>(); + options.UseSerializer, IMessage>(); }); - builder.Services.AddSingleton, ConsoleHandler>(); + builder.Services.AddSingleton, ConsoleHandler>(); // WEB:APP var app = builder.Build(); diff --git a/src/Web/Insight.Web/Services/ServiceHost.cs b/src/Web/Insight.Web/Services/ServiceHost.cs index d94e6ad..2c85602 100644 --- a/src/Web/Insight.Web/Services/ServiceHost.cs +++ b/src/Web/Insight.Web/Services/ServiceHost.cs @@ -25,6 +25,6 @@ public class ServiceHost : IHostedService public async Task StopAsync(CancellationToken cancellationToken) { - + } } diff --git a/src/Web/Insight.Web/Services/SessionHandler.cs b/src/Web/Insight.Web/Services/SessionHandler.cs index 94b4d37..330d09a 100644 --- a/src/Web/Insight.Web/Services/SessionHandler.cs +++ b/src/Web/Insight.Web/Services/SessionHandler.cs @@ -9,7 +9,7 @@ namespace Insight.Web.Services; public class SessionHandler : CircuitHandler { public SessionState State { get; } = new(); - + private readonly ChatService _chatService; private readonly SessionPool _sessionPool; private readonly AuthenticationStateProvider _authenticationState;