From 4c40e8871839e077c08d904e8db9b3619021d30e Mon Sep 17 00:00:00 2001 From: Claude Agent Date: Thu, 19 Mar 2026 14:53:35 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20Phase=208=20=E2=80=94=20Network=20Disco?= =?UTF-8?q?very=20+=20Windows=20Dev-Setup-Skripte?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Network Discovery: - Go Agent: internal/scanner/scanner.go mit TCP-Sweep (Port 445/80/22/443), ARP-Tabellen-Parser (Windows: arp -a, Linux: /proc/net/arp), Reverse-DNS, 50 gleichzeitige Goroutines mit Semaphore - Go Agent main.go: COMMAND_TYPE_NETWORK_SCAN Case → scanner.Scan() → JSON stdout - Backend: NetworkDevice Model (Id, AgentId, IpAddress, MacAddress, Hostname, Vendor, IsManaged, FirstSeen, LastSeen) - Backend: EF Migration AddNetworkDevices + Index auf IpAddress + MacAddress - Backend: NetworkDevicesController GET /api/v1/network-devices + DELETE /{id} - Backend: AgentGrpcService.ProcessNetworkScanResultAsync — upsert via MAC, IsManaged=true wenn IP einem bekannten Agent entspricht - Frontend: NetworkPage.tsx mit Scan-Panel, Device-Tabelle, Filter, Delete - Frontend: App.tsx — 'Netzwerk' Nav-Eintrag mit Network Icon Windows Dev-Setup: - dev-start.ps1 — Startet Docker/Postgres, EF-Migrationen, Backend+Frontend in separaten PowerShell-Fenstern; Voraussetzungen-Check (docker/dotnet/node/go) - dev-stop.ps1 — Stoppt alle NexusRMM-Prozesse + PostgreSQL Container - build-agent.ps1 — Baut nexus-agent.exe (Windows) + optional nexus-agent-linux Co-Authored-By: Claude Sonnet 4.6 --- Agent/cmd/agent/main.go | 17 + Agent/internal/scanner/scanner.go | 274 ++++++++++++ .../Controllers/NetworkDevicesController.cs | 52 +++ .../GrpcServices/AgentGrpcService.cs | 80 +++- .../src/NexusRMM.Core/Models/NetworkDevice.cs | 14 + .../Data/RmmDbContext.cs | 8 + ...260319135017_AddNetworkDevices.Designer.cs | 413 ++++++++++++++++++ .../20260319135017_AddNetworkDevices.cs | 53 +++ .../Migrations/RmmDbContextModelSnapshot.cs | 59 ++- Frontend/src/App.tsx | 7 +- Frontend/src/api/client.ts | 20 + Frontend/src/api/types.ts | 12 + Frontend/src/pages/NetworkPage.tsx | 285 ++++++++++++ build-agent.ps1 | 169 +++++++ dev-start.ps1 | 188 ++++++++ dev-stop.ps1 | 95 ++++ 16 files changed, 1733 insertions(+), 13 deletions(-) create mode 100644 Agent/internal/scanner/scanner.go create mode 100644 Backend/src/NexusRMM.Api/Controllers/NetworkDevicesController.cs create mode 100644 Backend/src/NexusRMM.Core/Models/NetworkDevice.cs create mode 100644 Backend/src/NexusRMM.Infrastructure/Migrations/20260319135017_AddNetworkDevices.Designer.cs create mode 100644 Backend/src/NexusRMM.Infrastructure/Migrations/20260319135017_AddNetworkDevices.cs create mode 100644 Frontend/src/pages/NetworkPage.tsx create mode 100644 build-agent.ps1 create mode 100644 dev-start.ps1 create mode 100644 dev-stop.ps1 diff --git a/Agent/cmd/agent/main.go b/Agent/cmd/agent/main.go index 89892a9..a20db53 100644 --- a/Agent/cmd/agent/main.go +++ b/Agent/cmd/agent/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "encoding/json" "fmt" "log" "os" @@ -16,6 +17,7 @@ import ( "nexusrmm.local/agent/internal/deployer" "nexusrmm.local/agent/internal/executor" "nexusrmm.local/agent/internal/meshagent" + "nexusrmm.local/agent/internal/scanner" pb "nexusrmm.local/agent/pkg/proto" ) @@ -142,6 +144,21 @@ func executeCommand(ctx context.Context, client *connection.GrpcClient, agentID result = deployer.Install(ctx, cmd.Payload) case pb.CommandType_COMMAND_TYPE_UNINSTALL_SOFTWARE: result = deployer.Uninstall(ctx, cmd.Payload) + case pb.CommandType_COMMAND_TYPE_NETWORK_SCAN: + var params struct { + Subnet string `json:"subnet"` + } + _ = json.Unmarshal([]byte(cmd.Payload), ¶ms) + devices, err := scanner.Scan(ctx, params.Subnet) + if err != nil { + result = &executor.Result{ExitCode: 1, Stderr: err.Error()} + } else { + result = &executor.Result{ + ExitCode: 0, + Stdout: scanner.ToJSON(devices), + Success: true, + } + } default: result = &executor.Result{ExitCode: -1, Stderr: fmt.Sprintf("unknown command type: %v", cmd.Type)} } diff --git a/Agent/internal/scanner/scanner.go b/Agent/internal/scanner/scanner.go new file mode 100644 index 0000000..e73032e --- /dev/null +++ b/Agent/internal/scanner/scanner.go @@ -0,0 +1,274 @@ +package scanner + +import ( + "context" + "encoding/json" + "fmt" + "net" + "os/exec" + "runtime" + "strings" + "sync" + "time" +) + +// Device represents a discovered network device. +type Device struct { + IP string `json:"ip"` + MAC string `json:"mac"` + Hostname string `json:"hostname"` + Vendor string `json:"vendor"` +} + +// Scan scans the given subnet (e.g. "192.168.1.0/24"). +// If subnet is empty, the local network is auto-detected. +func Scan(ctx context.Context, subnet string) ([]Device, error) { + // Auto-detect subnet if not provided + if subnet == "" { + detected, err := detectLocalSubnet() + if err != nil { + return nil, fmt.Errorf("auto-detect subnet: %w", err) + } + subnet = detected + } + + // Parse CIDR + _, ipNet, err := net.ParseCIDR(subnet) + if err != nil { + return nil, fmt.Errorf("parse subnet %q: %w", subnet, err) + } + + // Collect all host IPs in the subnet + hosts := hostsInNet(ipNet) + + // Concurrent ping sweep using TCP fallback (no raw ICMP needed) + const maxConcurrent = 50 + sem := make(chan struct{}, maxConcurrent) + var mu sync.Mutex + alive := make(map[string]bool) + var wg sync.WaitGroup + + for _, ip := range hosts { + // Check context before spawning + select { + case <-ctx.Done(): + break + default: + } + + wg.Add(1) + sem <- struct{}{} + go func(ipStr string) { + defer wg.Done() + defer func() { <-sem }() + + if isAlive(ipStr) { + mu.Lock() + alive[ipStr] = true + mu.Unlock() + } + }(ip.String()) + } + wg.Wait() + + if len(alive) == 0 { + return []Device{}, nil + } + + // Read ARP table to get MAC addresses + arpTable, err := readARPTable() + if err != nil { + // Non-fatal: continue without MAC info + arpTable = map[string]string{} + } + + // Build results with reverse DNS lookups + var devices []Device + for ip := range alive { + d := Device{IP: ip} + + if mac, ok := arpTable[ip]; ok { + d.MAC = mac + } + + // Reverse DNS lookup with short timeout + hostname := reverseLookup(ip) + d.Hostname = hostname + + devices = append(devices, d) + } + + return devices, nil +} + +// ToJSON serialises a slice of Devices to a JSON string. +func ToJSON(devices []Device) string { + b, _ := json.Marshal(devices) + return string(b) +} + +// detectLocalSubnet returns the CIDR of the first non-loopback IPv4 interface. +func detectLocalSubnet() (string, error) { + ifaces, err := net.Interfaces() + if err != nil { + return "", err + } + for _, iface := range ifaces { + if iface.Flags&net.FlagLoopback != 0 || iface.Flags&net.FlagUp == 0 { + continue + } + addrs, err := iface.Addrs() + if err != nil { + continue + } + for _, addr := range addrs { + var ip net.IP + var mask net.IPMask + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + mask = v.Mask + case *net.IPAddr: + ip = v.IP + } + if ip == nil || ip.IsLoopback() { + continue + } + ip = ip.To4() + if ip == nil { + continue + } + // Reconstruct CIDR from network address + network := ip.Mask(mask) + ones, _ := mask.Size() + return fmt.Sprintf("%s/%d", network.String(), ones), nil + } + } + return "", fmt.Errorf("no suitable network interface found") +} + +// hostsInNet returns all usable host addresses within the given network. +func hostsInNet(ipNet *net.IPNet) []net.IP { + var ips []net.IP + // Start from network address, increment + ip := cloneIP(ipNet.IP) + // Increment past network address + inc(ip) + for ipNet.Contains(ip) { + // Skip broadcast (last address) + next := cloneIP(ip) + inc(next) + if !ipNet.Contains(next) { + break // current ip is broadcast, stop + } + ips = append(ips, cloneIP(ip)) + inc(ip) + } + return ips +} + +func cloneIP(ip net.IP) net.IP { + clone := make(net.IP, len(ip)) + copy(clone, ip) + return clone +} + +func inc(ip net.IP) { + for j := len(ip) - 1; j >= 0; j-- { + ip[j]++ + if ip[j] > 0 { + break + } + } +} + +// isAlive attempts a TCP connection to common ports to determine if a host is up. +func isAlive(ip string) bool { + timeout := 300 * time.Millisecond + ports := []string{"445", "80", "22", "443"} + for _, port := range ports { + conn, err := net.DialTimeout("tcp", net.JoinHostPort(ip, port), timeout) + if err == nil { + conn.Close() + return true + } + } + return false +} + +// readARPTable reads the ARP cache and returns a map of IP -> MAC. +func readARPTable() (map[string]string, error) { + table := make(map[string]string) + if runtime.GOOS == "windows" { + return readARPWindows(table) + } + return readARPLinux(table) +} + +// readARPWindows parses `arp -a` output on Windows. +// Example line: " 192.168.1.1 aa-bb-cc-dd-ee-ff dynamic" +func readARPWindows(table map[string]string) (map[string]string, error) { + out, err := exec.Command("arp", "-a").Output() + if err != nil { + return table, err + } + for _, line := range strings.Split(string(out), "\n") { + line = strings.TrimSpace(line) + fields := strings.Fields(line) + if len(fields) < 2 { + continue + } + ip := fields[0] + if net.ParseIP(ip) == nil { + continue + } + mac := fields[1] + // Normalise aa-bb-cc-dd-ee-ff → aa:bb:cc:dd:ee:ff + mac = strings.ReplaceAll(mac, "-", ":") + if len(mac) == 17 { + table[ip] = mac + } + } + return table, nil +} + +// readARPLinux parses /proc/net/arp on Linux. +// Format: IP address HW type Flags HW address Mask Device +func readARPLinux(table map[string]string) (map[string]string, error) { + data, err := readFile("/proc/net/arp") + if err != nil { + return table, err + } + lines := strings.Split(string(data), "\n") + // Skip header line + for _, line := range lines[1:] { + fields := strings.Fields(line) + if len(fields) < 4 { + continue + } + ip := fields[0] + mac := fields[3] + if net.ParseIP(ip) != nil && len(mac) == 17 && mac != "00:00:00:00:00:00" { + table[ip] = mac + } + } + return table, nil +} + +// readFile is a thin wrapper so we can test Linux ARP parsing on any OS. +func readFile(path string) ([]byte, error) { + return exec.Command("cat", path).Output() +} + +// reverseLookup returns the hostname for an IP via reverse DNS, with a short timeout. +func reverseLookup(ip string) string { + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + + names, err := net.DefaultResolver.LookupAddr(ctx, ip) + if err != nil || len(names) == 0 { + return "" + } + // Strip trailing dot from FQDN + return strings.TrimSuffix(names[0], ".") +} diff --git a/Backend/src/NexusRMM.Api/Controllers/NetworkDevicesController.cs b/Backend/src/NexusRMM.Api/Controllers/NetworkDevicesController.cs new file mode 100644 index 0000000..9ce7453 --- /dev/null +++ b/Backend/src/NexusRMM.Api/Controllers/NetworkDevicesController.cs @@ -0,0 +1,52 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using NexusRMM.Infrastructure.Data; + +namespace NexusRMM.Api.Controllers; + +[ApiController] +[Route("api/v1/network-devices")] +public class NetworkDevicesController : ControllerBase +{ + private readonly RmmDbContext _db; + public NetworkDevicesController(RmmDbContext db) => _db = db; + + [HttpGet] + public async Task GetAll([FromQuery] Guid? agentId) + { + var query = _db.NetworkDevices.AsQueryable(); + + if (agentId.HasValue) + query = query.Where(d => d.AgentId == agentId.Value); + + var devices = await query + .OrderBy(d => d.IpAddress) + .Select(d => new + { + d.Id, + d.AgentId, + d.IpAddress, + d.MacAddress, + d.Hostname, + d.Vendor, + d.IsManaged, + d.FirstSeen, + d.LastSeen + }) + .ToListAsync(); + + return Ok(devices); + } + + [HttpDelete("{id:int}")] + public async Task Delete(int id) + { + var device = await _db.NetworkDevices.FindAsync(id); + if (device is null) + return NotFound(); + + _db.NetworkDevices.Remove(device); + await _db.SaveChangesAsync(); + return NoContent(); + } +} diff --git a/Backend/src/NexusRMM.Api/GrpcServices/AgentGrpcService.cs b/Backend/src/NexusRMM.Api/GrpcServices/AgentGrpcService.cs index ceb366c..58485bb 100644 --- a/Backend/src/NexusRMM.Api/GrpcServices/AgentGrpcService.cs +++ b/Backend/src/NexusRMM.Api/GrpcServices/AgentGrpcService.cs @@ -114,12 +114,12 @@ public class AgentGrpcService : AgentService.AgentServiceBase public override async Task ReportCommandResult(CommandResult request, ServerCallContext context) { var taskId = Guid.Parse(request.CommandId); - var task = await _db.Tasks.FindAsync(taskId) + var taskItem = await _db.Tasks.FindAsync(taskId) ?? throw new RpcException(new Status(StatusCode.NotFound, "Task not found")); - task.Status = request.Success ? CoreTaskStatus.Completed : CoreTaskStatus.Failed; - task.CompletedAt = DateTime.UtcNow; - task.Result = JsonSerializer.SerializeToElement(new + taskItem.Status = request.Success ? CoreTaskStatus.Completed : CoreTaskStatus.Failed; + taskItem.CompletedAt = DateTime.UtcNow; + taskItem.Result = JsonSerializer.SerializeToElement(new { request.ExitCode, request.Stdout, @@ -129,6 +129,11 @@ public class AgentGrpcService : AgentService.AgentServiceBase await _db.SaveChangesAsync(); + if (taskItem.Type == NexusRMM.Core.Models.TaskType.NetworkScan && request.Success && !string.IsNullOrWhiteSpace(request.Stdout)) + { + await ProcessNetworkScanResultAsync(request.AgentId, request.Stdout); + } + // SignalR: Command-Ergebnis an agent-Gruppe pushen await _hub.Clients.Group($"agent-{request.AgentId}") .CommandResultUpdated(request.CommandId, request.AgentId, request.Success, request.ExitCode); @@ -136,6 +141,73 @@ public class AgentGrpcService : AgentService.AgentServiceBase return new CommandResultResponse(); } + private async Task ProcessNetworkScanResultAsync(string agentIdStr, string stdout) + { + try + { + var scannedDevices = JsonSerializer.Deserialize>(stdout, new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }); + + if (scannedDevices is null || scannedDevices.Count == 0) + return; + + Guid? agentId = Guid.TryParse(agentIdStr, out var parsedId) ? parsedId : null; + + var knownAgentIps = await _db.Agents + .Select(a => a.IpAddress) + .Where(ip => ip != null && ip != string.Empty) + .ToHashSetAsync(); + + var now = DateTime.UtcNow; + + foreach (var scanned in scannedDevices) + { + if (string.IsNullOrWhiteSpace(scanned.Mac)) + continue; + + var existing = await _db.NetworkDevices + .FirstOrDefaultAsync(d => d.MacAddress == scanned.Mac); + + if (existing is not null) + { + existing.LastSeen = now; + existing.IpAddress = scanned.Ip ?? existing.IpAddress; + existing.IsManaged = knownAgentIps.Contains(scanned.Ip ?? string.Empty); + } + else + { + _db.NetworkDevices.Add(new NexusRMM.Core.Models.NetworkDevice + { + AgentId = agentId, + IpAddress = scanned.Ip ?? string.Empty, + MacAddress = scanned.Mac, + Hostname = scanned.Hostname ?? string.Empty, + Vendor = scanned.Vendor ?? string.Empty, + IsManaged = knownAgentIps.Contains(scanned.Ip ?? string.Empty), + FirstSeen = now, + LastSeen = now + }); + } + } + + await _db.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to process NetworkScan result for agent {AgentId}", agentIdStr); + } + } + + private class ScanDevice + { + public string? Ip { get; set; } + public string? Mac { get; set; } + public string? Hostname { get; set; } + public string? Vendor { get; set; } + } + private static CommandType MapTaskType(NexusRMM.Core.Models.TaskType type) => type switch { NexusRMM.Core.Models.TaskType.Shell => CommandType.Shell, diff --git a/Backend/src/NexusRMM.Core/Models/NetworkDevice.cs b/Backend/src/NexusRMM.Core/Models/NetworkDevice.cs new file mode 100644 index 0000000..6a2efc0 --- /dev/null +++ b/Backend/src/NexusRMM.Core/Models/NetworkDevice.cs @@ -0,0 +1,14 @@ +namespace NexusRMM.Core.Models; + +public class NetworkDevice +{ + public int Id { get; set; } + public Guid? AgentId { get; set; } // Welcher Agent hat es entdeckt + public string IpAddress { get; set; } = string.Empty; + public string MacAddress { get; set; } = string.Empty; + public string Hostname { get; set; } = string.Empty; + public string Vendor { get; set; } = string.Empty; + public bool IsManaged { get; set; } // Ist dieses Gerät ein bekannter RMM-Agent? + public DateTime FirstSeen { get; set; } + public DateTime LastSeen { get; set; } +} diff --git a/Backend/src/NexusRMM.Infrastructure/Data/RmmDbContext.cs b/Backend/src/NexusRMM.Infrastructure/Data/RmmDbContext.cs index b8045b0..3e1f731 100644 --- a/Backend/src/NexusRMM.Infrastructure/Data/RmmDbContext.cs +++ b/Backend/src/NexusRMM.Infrastructure/Data/RmmDbContext.cs @@ -14,6 +14,7 @@ public class RmmDbContext : DbContext public DbSet AlertRules => Set(); public DbSet Alerts => Set(); public DbSet SoftwarePackages => Set(); + public DbSet NetworkDevices => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -65,5 +66,12 @@ public class RmmDbContext : DbContext e.HasKey(p => p.Id); e.HasIndex(p => new { p.Name, p.Version, p.OsType }).IsUnique(); }); + + modelBuilder.Entity(e => + { + e.HasKey(d => d.Id); + e.HasIndex(d => d.IpAddress); + e.HasIndex(d => d.MacAddress); + }); } } diff --git a/Backend/src/NexusRMM.Infrastructure/Migrations/20260319135017_AddNetworkDevices.Designer.cs b/Backend/src/NexusRMM.Infrastructure/Migrations/20260319135017_AddNetworkDevices.Designer.cs new file mode 100644 index 0000000..e285776 --- /dev/null +++ b/Backend/src/NexusRMM.Infrastructure/Migrations/20260319135017_AddNetworkDevices.Designer.cs @@ -0,0 +1,413 @@ +// +using System; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using NexusRMM.Infrastructure.Data; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace NexusRMM.Infrastructure.Migrations +{ + [DbContext(typeof(RmmDbContext))] + [Migration("20260319135017_AddNetworkDevices")] + partial class AddNetworkDevices + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.5") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("NexusRMM.Core.Models.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentVersion") + .IsRequired() + .HasColumnType("text"); + + b.Property("EnrolledAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddress") + .IsRequired() + .HasColumnType("text"); + + b.Property("LastSeen") + .HasColumnType("timestamp with time zone"); + + b.Property("MacAddress") + .IsRequired() + .HasColumnType("text"); + + b.Property("MeshAgentId") + .HasColumnType("text"); + + b.Property("OsType") + .HasColumnType("integer"); + + b.Property("OsVersion") + .IsRequired() + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("integer"); + + b.PrimitiveCollection("Tags") + .IsRequired() + .HasColumnType("jsonb"); + + b.HasKey("Id"); + + b.HasIndex("Hostname"); + + b.HasIndex("MacAddress"); + + b.ToTable("Agents"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Metrics") + .HasColumnType("jsonb"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("Timestamp"); + + b.ToTable("AgentMetrics"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.Alert", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Acknowledged") + .HasColumnType("boolean"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .IsRequired() + .HasColumnType("text"); + + b.Property("RuleId") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("RuleId"); + + b.ToTable("Alerts"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.AlertRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("MetricPath") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Operator") + .IsRequired() + .HasColumnType("text"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Threshold") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.ToTable("AlertRules"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.NetworkDevice", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("FirstSeen") + .HasColumnType("timestamp with time zone"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddress") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsManaged") + .HasColumnType("boolean"); + + b.Property("LastSeen") + .HasColumnType("timestamp with time zone"); + + b.Property("MacAddress") + .IsRequired() + .HasColumnType("text"); + + b.Property("Vendor") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("MacAddress"); + + b.ToTable("NetworkDevices"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.SoftwarePackage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Checksum") + .HasColumnType("text"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("InstallerUrl") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OsType") + .HasColumnType("integer"); + + b.Property("PackageManager") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageName") + .IsRequired() + .HasColumnType("text"); + + b.Property("SilentArgs") + .HasColumnType("text"); + + b.Property("Version") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Name", "Version", "OsType") + .IsUnique(); + + b.ToTable("SoftwarePackages"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.TaskItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Payload") + .HasColumnType("jsonb"); + + b.Property("Result") + .HasColumnType("jsonb"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Type") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.ToTable("Tasks"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.Ticket", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.ToTable("Tickets"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b => + { + b.HasOne("NexusRMM.Core.Models.Agent", "Agent") + .WithMany("Metrics") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.Alert", b => + { + b.HasOne("NexusRMM.Core.Models.Agent", "Agent") + .WithMany("Alerts") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NexusRMM.Core.Models.AlertRule", "Rule") + .WithMany("Alerts") + .HasForeignKey("RuleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Rule"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.TaskItem", b => + { + b.HasOne("NexusRMM.Core.Models.Agent", "Agent") + .WithMany("Tasks") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.Ticket", b => + { + b.HasOne("NexusRMM.Core.Models.Agent", "Agent") + .WithMany("Tickets") + .HasForeignKey("AgentId"); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.Agent", b => + { + b.Navigation("Alerts"); + + b.Navigation("Metrics"); + + b.Navigation("Tasks"); + + b.Navigation("Tickets"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.AlertRule", b => + { + b.Navigation("Alerts"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Backend/src/NexusRMM.Infrastructure/Migrations/20260319135017_AddNetworkDevices.cs b/Backend/src/NexusRMM.Infrastructure/Migrations/20260319135017_AddNetworkDevices.cs new file mode 100644 index 0000000..09a2898 --- /dev/null +++ b/Backend/src/NexusRMM.Infrastructure/Migrations/20260319135017_AddNetworkDevices.cs @@ -0,0 +1,53 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace NexusRMM.Infrastructure.Migrations +{ + /// + public partial class AddNetworkDevices : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "NetworkDevices", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + AgentId = table.Column(type: "uuid", nullable: true), + IpAddress = table.Column(type: "text", nullable: false), + MacAddress = table.Column(type: "text", nullable: false), + Hostname = table.Column(type: "text", nullable: false), + Vendor = table.Column(type: "text", nullable: false), + IsManaged = table.Column(type: "boolean", nullable: false), + FirstSeen = table.Column(type: "timestamp with time zone", nullable: false), + LastSeen = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NetworkDevices", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_NetworkDevices_IpAddress", + table: "NetworkDevices", + column: "IpAddress"); + + migrationBuilder.CreateIndex( + name: "IX_NetworkDevices_MacAddress", + table: "NetworkDevices", + column: "MacAddress"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "NetworkDevices"); + } + } +} diff --git a/Backend/src/NexusRMM.Infrastructure/Migrations/RmmDbContextModelSnapshot.cs b/Backend/src/NexusRMM.Infrastructure/Migrations/RmmDbContextModelSnapshot.cs index 2fd4749..ed69211 100644 --- a/Backend/src/NexusRMM.Infrastructure/Migrations/RmmDbContextModelSnapshot.cs +++ b/Backend/src/NexusRMM.Infrastructure/Migrations/RmmDbContextModelSnapshot.cs @@ -74,7 +74,7 @@ namespace NexusRMM.Infrastructure.Migrations b.HasIndex("MacAddress"); - b.ToTable("Agents", (string)null); + b.ToTable("Agents"); }); modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b => @@ -100,7 +100,7 @@ namespace NexusRMM.Infrastructure.Migrations b.HasIndex("Timestamp"); - b.ToTable("AgentMetrics", (string)null); + b.ToTable("AgentMetrics"); }); modelBuilder.Entity("NexusRMM.Core.Models.Alert", b => @@ -138,7 +138,7 @@ namespace NexusRMM.Infrastructure.Migrations b.HasIndex("RuleId"); - b.ToTable("Alerts", (string)null); + b.ToTable("Alerts"); }); modelBuilder.Entity("NexusRMM.Core.Models.AlertRule", b => @@ -172,7 +172,52 @@ namespace NexusRMM.Infrastructure.Migrations b.HasKey("Id"); - b.ToTable("AlertRules", (string)null); + b.ToTable("AlertRules"); + }); + + modelBuilder.Entity("NexusRMM.Core.Models.NetworkDevice", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("FirstSeen") + .HasColumnType("timestamp with time zone"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddress") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsManaged") + .HasColumnType("boolean"); + + b.Property("LastSeen") + .HasColumnType("timestamp with time zone"); + + b.Property("MacAddress") + .IsRequired() + .HasColumnType("text"); + + b.Property("Vendor") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("MacAddress"); + + b.ToTable("NetworkDevices"); }); modelBuilder.Entity("NexusRMM.Core.Models.SoftwarePackage", b => @@ -219,7 +264,7 @@ namespace NexusRMM.Infrastructure.Migrations b.HasIndex("Name", "Version", "OsType") .IsUnique(); - b.ToTable("SoftwarePackages", (string)null); + b.ToTable("SoftwarePackages"); }); modelBuilder.Entity("NexusRMM.Core.Models.TaskItem", b => @@ -253,7 +298,7 @@ namespace NexusRMM.Infrastructure.Migrations b.HasIndex("AgentId"); - b.ToTable("Tasks", (string)null); + b.ToTable("Tasks"); }); modelBuilder.Entity("NexusRMM.Core.Models.Ticket", b => @@ -291,7 +336,7 @@ namespace NexusRMM.Infrastructure.Migrations b.HasIndex("AgentId"); - b.ToTable("Tickets", (string)null); + b.ToTable("Tickets"); }); modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b => diff --git a/Frontend/src/App.tsx b/Frontend/src/App.tsx index eeb5dbc..c32db1a 100644 --- a/Frontend/src/App.tsx +++ b/Frontend/src/App.tsx @@ -1,11 +1,12 @@ import { useState } from 'react' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { LayoutDashboard, Ticket, Bell, Package, Menu, X } from 'lucide-react' +import { LayoutDashboard, Ticket, Bell, Package, Network, Menu, X } from 'lucide-react' import { DashboardPage } from './pages/DashboardPage' import { AgentDetailPage } from './pages/AgentDetailPage' import TicketsPage from './pages/TicketsPage' import AlertsPage from './pages/AlertsPage' import SoftwarePage from './pages/SoftwarePage' +import NetworkPage from './pages/NetworkPage' import { cn } from './lib/utils' const queryClient = new QueryClient({ @@ -17,7 +18,7 @@ const queryClient = new QueryClient({ }, }) -type Page = 'dashboard' | 'agent-detail' | 'tickets' | 'alerts' | 'software' +type Page = 'dashboard' | 'agent-detail' | 'tickets' | 'alerts' | 'network' | 'software' interface NavItem { id: Page @@ -29,6 +30,7 @@ const navItems: NavItem[] = [ { id: 'dashboard', label: 'Dashboard', icon: }, { id: 'tickets', label: 'Tickets', icon: }, { id: 'alerts', label: 'Alerts', icon: }, + { id: 'network', label: 'Netzwerk', icon: }, { id: 'software', label: 'Software', icon: }, ] @@ -112,6 +114,7 @@ function AppContent() { )} {page === 'tickets' && } {page === 'alerts' && } + {page === 'network' && } {page === 'software' && } diff --git a/Frontend/src/api/client.ts b/Frontend/src/api/client.ts index 2d8e5d4..de3ba60 100644 --- a/Frontend/src/api/client.ts +++ b/Frontend/src/api/client.ts @@ -15,6 +15,7 @@ import type { DeployRequest, DeployResponse, RemoteSessionInfo, + NetworkDevice, } from './types' const BASE_URL = '/api/v1' @@ -104,3 +105,22 @@ export const remoteDesktopApi = { getSession: (agentId: string) => request(`/agents/${agentId}/remote-session`), } + +// Network Devices +export const networkDevicesApi = { + list: (agentId?: string) => { + const param = agentId ? `?agentId=${agentId}` : '' + return request(`/network-devices${param}`) + }, + delete: (id: number) => + request(`/network-devices/${id}`, { method: 'DELETE' }), +} + +// Network Scan triggern (nutzt tasksApi intern) +export const networkScanApi = { + trigger: (agentId: string, subnet?: string) => + request('/tasks', { + method: 'POST', + body: JSON.stringify({ agentId, type: 'NetworkScan', payload: { subnet: subnet ?? '' } }), + }), +} diff --git a/Frontend/src/api/types.ts b/Frontend/src/api/types.ts index 48d8e08..f9c71bc 100644 --- a/Frontend/src/api/types.ts +++ b/Frontend/src/api/types.ts @@ -184,3 +184,15 @@ export interface RemoteSessionInfo { sessionUrl?: string meshCentralBaseUrl?: string } + +export interface NetworkDevice { + id: number + agentId: string | null + ipAddress: string + macAddress: string + hostname: string + vendor: string + isManaged: boolean + firstSeen: string + lastSeen: string +} diff --git a/Frontend/src/pages/NetworkPage.tsx b/Frontend/src/pages/NetworkPage.tsx new file mode 100644 index 0000000..caff99d --- /dev/null +++ b/Frontend/src/pages/NetworkPage.tsx @@ -0,0 +1,285 @@ +import { useState } from 'react' +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { Network, Trash2, Play, Wifi, WifiOff } from 'lucide-react' +import { networkDevicesApi, networkScanApi } from '../api/client' +import { cn } from '../lib/utils' + +function formatRelativeTime(dateString: string): string { + const now = new Date() + const date = new Date(dateString) + const diffMs = now.getTime() - date.getTime() + + const diffSeconds = Math.floor(diffMs / 1000) + const diffMinutes = Math.floor(diffSeconds / 60) + const diffHours = Math.floor(diffMinutes / 60) + const diffDays = Math.floor(diffHours / 24) + + if (diffSeconds < 60) { + return 'gerade eben' + } + if (diffMinutes < 60) { + return `vor ${diffMinutes} Min.` + } + if (diffHours < 24) { + return `vor ${diffHours} Std.` + } + return `vor ${diffDays} Tagen` +} + +export default function NetworkPage() { + const [agentIdInput, setAgentIdInput] = useState('') + const [subnetInput, setSubnetInput] = useState('') + const [filterUnknown, setFilterUnknown] = useState(false) + const [isScanPending, setIsScanPending] = useState(false) + + const queryClient = useQueryClient() + + const devicesQuery = useQuery({ + queryKey: ['networkDevices'], + queryFn: () => networkDevicesApi.list(), + }) + + const scanMutation = useMutation({ + mutationFn: ({ agentId, subnet }: { agentId: string; subnet?: string }) => + networkScanApi.trigger(agentId, subnet), + onSuccess: () => { + setIsScanPending(true) + // Refresh after a brief delay to show updated results + setTimeout(() => { + queryClient.invalidateQueries({ queryKey: ['networkDevices'] }) + setIsScanPending(false) + }, 3000) + }, + onError: () => { + setIsScanPending(false) + }, + }) + + const deleteMutation = useMutation({ + mutationFn: (id: number) => networkDevicesApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['networkDevices'] }) + }, + }) + + const handleScan = () => { + if (!agentIdInput.trim()) return + setIsScanPending(true) + scanMutation.mutate({ + agentId: agentIdInput.trim(), + subnet: subnetInput.trim() || undefined, + }) + } + + const handleDelete = (id: number) => { + if (window.confirm('Möchten Sie dieses Gerät wirklich löschen?')) { + deleteMutation.mutate(id) + } + } + + const devices = devicesQuery.data ?? [] + const filteredDevices = filterUnknown + ? devices.filter((d) => !d.isManaged) + : devices + + return ( +
+ {/* Header */} +
+ +
+

Netzwerk-Discovery

+

+ Geräte im Netzwerk erkennen und verwalten +

+
+
+ + {/* Scan Panel */} +
+

Netzwerk-Scan starten

+
+ setAgentIdInput(e.target.value)} + placeholder="Agent-ID (erforderlich)" + className="flex-1 bg-background border border-border rounded-lg px-3 py-2 text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary" + /> + setSubnetInput(e.target.value)} + placeholder="Subnetz (optional, z.B. 192.168.1.0/24)" + className="flex-1 bg-background border border-border rounded-lg px-3 py-2 text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary" + /> + +
+ {scanMutation.isError && ( +

+ Fehler beim Starten des Scans: {String(scanMutation.error)} +

+ )} + {isScanPending && !scanMutation.isError && ( +

+ + Scan wurde gestartet. Ergebnisse werden in Kürze aktualisiert... +

+ )} +
+ + {/* Results Table */} +
+
+

+ Erkannte Geräte + {devicesQuery.isSuccess && ( + + ({filteredDevices.length} von {devices.length}) + + )} +

+ + {/* Filter Toggle */} +
+ + +
+
+ + {/* Loading State */} + {devicesQuery.isLoading && ( +

Lädt...

+ )} + + {/* Error State */} + {devicesQuery.isError && ( +

+ Fehler beim Laden der Geräte +

+ )} + + {/* Empty State */} + {devicesQuery.isSuccess && filteredDevices.length === 0 && ( +
+ +

+ {filterUnknown + ? 'Keine unbekannten Geräte gefunden' + : 'Keine Geräte gefunden. Starten Sie einen Scan.'} +

+
+ )} + + {/* Table */} + {devicesQuery.isSuccess && filteredDevices.length > 0 && ( +
+ + + + + + + + + + + + + + {filteredDevices.map((device) => ( + + + + + + + + + + ))} + +
+ IP-Adresse + + MAC-Adresse + + Hostname + + Hersteller + + Status + + Zuletzt gesehen + + Aktion +
+ {device.ipAddress} + + {device.macAddress || '—'} + + {device.hostname || '—'} + + {device.vendor || '—'} + + {device.isManaged ? ( + + + Verwaltet + + ) : ( + + + Unbekannt + + )} + + {formatRelativeTime(device.lastSeen)} + + +
+
+ )} +
+
+ ) +} diff --git a/build-agent.ps1 b/build-agent.ps1 new file mode 100644 index 0000000..00ab544 --- /dev/null +++ b/build-agent.ps1 @@ -0,0 +1,169 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Baut den NexusRMM Agent für Windows (und optional Linux/amd64) +.DESCRIPTION + Sucht die Go-Binary, baut den Agent für Windows und optional für Linux. + Erstellt eine Standard-Konfigurationsdatei, wenn noch keine vorhanden ist. +.PARAMETER Linux + Baut zusätzlich eine Linux-Binary (nexus-agent-linux). +.EXAMPLE + .\build-agent.ps1 + .\build-agent.ps1 -Linux +#> +param( + [switch]$Linux +) + +$ErrorActionPreference = "Stop" +$AgentDir = "D:\001_Projekte\IT_Tool\Agent" +$ConfigFile = "$AgentDir\nexus-agent.yaml" + +# --------------------------------------------------------------------------- +# Helper +# --------------------------------------------------------------------------- +function Write-Step { param($msg) Write-Host "`n==> $msg" -ForegroundColor Cyan } +function Write-OK { param($msg) Write-Host " [OK] $msg" -ForegroundColor Green } +function Write-Warn { param($msg) Write-Host " [!] $msg" -ForegroundColor Yellow } +function Write-Fail { param($msg) Write-Host " [FEHLER] $msg" -ForegroundColor Red } + +function Format-FileSize { + param([long]$Bytes) + if ($Bytes -ge 1MB) { return "{0:N1} MB" -f ($Bytes / 1MB) } + return "{0:N0} KB" -f ($Bytes / 1KB) +} + +# --------------------------------------------------------------------------- +# 1. Go-Binary finden +# --------------------------------------------------------------------------- +Write-Step "Suche Go-Installation..." + +# Kandidaten: expliziter Standardpfad zuerst, dann PATH +$goCandidates = @( + "C:\Program Files\Go\bin\go.exe", + "C:\Go\bin\go.exe" +) + +$goExe = $null + +foreach ($candidate in $goCandidates) { + if (Test-Path $candidate) { + $goExe = $candidate + break + } +} + +if ($null -eq $goExe) { + # Fallback: PATH + $fromPath = Get-Command "go" -ErrorAction SilentlyContinue + if ($null -ne $fromPath) { + $goExe = $fromPath.Source + } +} + +if ($null -eq $goExe) { + Write-Fail "Go wurde nicht gefunden. Bitte Go installieren (https://go.dev/dl/) oder PATH prüfen." + exit 1 +} + +$goVersion = & $goExe version +Write-OK "Go gefunden: $goExe" +Write-OK "Version: $goVersion" + +# --------------------------------------------------------------------------- +# 2. Ins Agent-Verzeichnis wechseln +# --------------------------------------------------------------------------- +if (-not (Test-Path $AgentDir)) { + Write-Fail "Agent-Verzeichnis nicht gefunden: $AgentDir" + exit 1 +} + +Push-Location $AgentDir +try { + + # ----------------------------------------------------------------------- + # 3. Windows-Build + # ----------------------------------------------------------------------- + Write-Step "Baue Windows-Binary (nexus-agent.exe)..." + + $env:GOOS = "windows" + $env:GOARCH = "amd64" + $env:CGO_ENABLED = "0" + + $winOut = "$AgentDir\nexus-agent.exe" + + & $goExe build -ldflags="-s -w" -o $winOut ./cmd/agent/ + if ($LASTEXITCODE -ne 0) { + Write-Fail "Windows-Build fehlgeschlagen." + exit 1 + } + + $winSize = (Get-Item $winOut).Length + Write-OK "Windows-Binary erstellt:" + Write-OK " Pfad: $winOut" + Write-OK " Groesse: $(Format-FileSize $winSize)" + + # ----------------------------------------------------------------------- + # 4. Linux-Build (optional) + # ----------------------------------------------------------------------- + if ($Linux) { + Write-Step "Baue Linux-Binary (nexus-agent-linux)..." + + $env:GOOS = "linux" + $env:GOARCH = "amd64" + $env:CGO_ENABLED = "0" + + $linuxOut = "$AgentDir\nexus-agent-linux" + + & $goExe build -ldflags="-s -w" -o $linuxOut ./cmd/agent/ + if ($LASTEXITCODE -ne 0) { + Write-Fail "Linux-Build fehlgeschlagen." + exit 1 + } + + $linuxSize = (Get-Item $linuxOut).Length + Write-OK "Linux-Binary erstellt:" + Write-OK " Pfad: $linuxOut" + Write-OK " Groesse: $(Format-FileSize $linuxSize)" + } else { + Write-Warn "Linux-Build übersprungen. Mit -Linux Parameter ausführen um Linux-Binary zu bauen." + } + +} finally { + # Umgebungsvariablen zurücksetzen + Remove-Item Env:\GOOS -ErrorAction SilentlyContinue + Remove-Item Env:\GOARCH -ErrorAction SilentlyContinue + Remove-Item Env:\CGO_ENABLED -ErrorAction SilentlyContinue + Pop-Location +} + +# --------------------------------------------------------------------------- +# 5. Konfigurationsdatei erstellen (nur wenn nicht vorhanden) +# --------------------------------------------------------------------------- +Write-Step "Prüfe Konfigurationsdatei..." + +if (Test-Path $ConfigFile) { + Write-OK "Konfiguration bereits vorhanden: $ConfigFile (wird nicht überschrieben)" +} else { + Write-Warn "Keine Konfigurationsdatei gefunden. Erstelle Standard-Konfiguration..." + + $defaultConfig = @" +# NexusRMM Agent Konfiguration +server_address: localhost:5001 +heartbeat_interval: 30 +tls_enabled: false +mesh_enabled: false +mesh_central_url: "" +"@ + + Set-Content -Path $ConfigFile -Value $defaultConfig -Encoding UTF8 + Write-OK "Konfiguration erstellt: $ConfigFile" +} + +# --------------------------------------------------------------------------- +# 6. Zusammenfassung +# --------------------------------------------------------------------------- +Write-Host "" +Write-Host "Build abgeschlossen." -ForegroundColor Green +Write-Host "Agent starten: .\Agent\nexus-agent.exe" -ForegroundColor Yellow +Write-Host "Konfiguration: $ConfigFile" -ForegroundColor Yellow diff --git a/dev-start.ps1 b/dev-start.ps1 new file mode 100644 index 0000000..e3d10d8 --- /dev/null +++ b/dev-start.ps1 @@ -0,0 +1,188 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Startet die NexusRMM Entwicklungsumgebung +.DESCRIPTION + Startet Docker (Postgres + MeshCentral), führt DB-Migrationen aus, + startet Backend und Frontend in separaten Fenstern. +#> + +$ErrorActionPreference = "Stop" +$Root = "D:\001_Projekte\IT_Tool" + +# --------------------------------------------------------------------------- +# Helper-Funktionen +# --------------------------------------------------------------------------- +function Write-Step { param($msg) Write-Host "`n==> $msg" -ForegroundColor Cyan } +function Write-OK { param($msg) Write-Host " [OK] $msg" -ForegroundColor Green } +function Write-Warn { param($msg) Write-Host " [!] $msg" -ForegroundColor Yellow } +function Write-Fail { param($msg) Write-Host " [FEHLER] $msg" -ForegroundColor Red } + +# --------------------------------------------------------------------------- +# 1. Voraussetzungen prüfen +# --------------------------------------------------------------------------- +Write-Step "Prüfe Voraussetzungen..." + +$missing = $false + +$tools = @( + @{ Name = "docker"; Desc = "Docker Desktop" }, + @{ Name = "dotnet"; Desc = ".NET SDK" }, + @{ Name = "node"; Desc = "Node.js" }, + @{ Name = "npm"; Desc = "npm" }, + @{ Name = "go"; Desc = "Go" } +) + +foreach ($tool in $tools) { + $cmd = Get-Command $tool.Name -ErrorAction SilentlyContinue + if ($null -eq $cmd) { + Write-Fail "$($tool.Desc) ($($tool.Name)) nicht gefunden. Bitte installieren." + $missing = $true + } else { + Write-OK "$($tool.Desc): $($cmd.Source)" + } +} + +if ($missing) { + Write-Fail "Fehlende Voraussetzungen – Abbruch." + exit 1 +} + +# dotnet-ef prüfen +$efInstalled = dotnet tool list --global 2>$null | Select-String "dotnet-ef" +if (-not $efInstalled) { + Write-Warn "dotnet-ef nicht global installiert. Installiere jetzt..." + dotnet tool install --global dotnet-ef + if ($LASTEXITCODE -ne 0) { + Write-Fail "dotnet-ef konnte nicht installiert werden." + exit 1 + } + Write-OK "dotnet-ef installiert." +} else { + Write-OK "dotnet-ef: vorhanden" +} + +# --------------------------------------------------------------------------- +# 2. PostgreSQL per Docker starten +# --------------------------------------------------------------------------- +Write-Step "Starte PostgreSQL..." + +Push-Location $Root +try { + docker compose up -d nexusrmm-postgres + if ($LASTEXITCODE -ne 0) { + Write-Fail "docker compose up fehlgeschlagen." + exit 1 + } +} finally { + Pop-Location +} + +# Warte bis PostgreSQL bereit ist (max 30 Sekunden, Intervall 2 Sekunden) +Write-Host " Warte auf PostgreSQL..." -ForegroundColor Cyan +$maxWait = 30 +$waited = 0 +$pgReady = $false + +while ($waited -lt $maxWait) { + $result = docker exec nexusrmm-postgres pg_isready -U nexusrmm -q 2>&1 + if ($LASTEXITCODE -eq 0) { + $pgReady = $true + break + } + Start-Sleep -Seconds 2 + $waited += 2 +} + +if (-not $pgReady) { + Write-Fail "PostgreSQL ist nach $maxWait Sekunden nicht erreichbar." + exit 1 +} +Write-OK "PostgreSQL bereit (Port 5433)." + +# --------------------------------------------------------------------------- +# 3. EF Core Migrationen ausführen +# --------------------------------------------------------------------------- +Write-Step "Führe Datenbank-Migrationen aus..." + +Push-Location "$Root\Backend" +try { + # --project: Migration-Projekt (Infrastructure enthält DbContext + Migrations) + # --startup-project: Startup-Projekt mit Verbindungsstring + dotnet ef database update ` + --project "src\NexusRMM.Infrastructure" ` + --startup-project "src\NexusRMM.Api" ` + --no-build + if ($LASTEXITCODE -ne 0) { + # --no-build schlägt fehl wenn noch kein Build vorhanden – Build nachholen + Write-Warn "Migration mit --no-build fehlgeschlagen, baue zuerst..." + dotnet build "src\NexusRMM.Api" --configuration Debug -q + if ($LASTEXITCODE -ne 0) { + Write-Fail "dotnet build fehlgeschlagen." + exit 1 + } + dotnet ef database update ` + --project "src\NexusRMM.Infrastructure" ` + --startup-project "src\NexusRMM.Api" + if ($LASTEXITCODE -ne 0) { + Write-Fail "dotnet ef database update fehlgeschlagen." + exit 1 + } + } +} finally { + Pop-Location +} +Write-OK "Migrationen erfolgreich." + +# --------------------------------------------------------------------------- +# 4. Backend in neuem PowerShell-Fenster starten +# --------------------------------------------------------------------------- +Write-Step "Starte Backend..." + +$backendCmd = "Set-Location '$Root\Backend'; Write-Host 'NexusRMM Backend' -ForegroundColor Cyan; dotnet run --project src/NexusRMM.Api" + +Start-Process powershell -ArgumentList @( + "-NoExit", + "-Command", + $backendCmd +) -WindowStyle Normal + +Write-OK "Backend-Fenster geöffnet." + +# --------------------------------------------------------------------------- +# 5. Kurz warten damit das Backend starten kann +# --------------------------------------------------------------------------- +Write-Host "`n Warte 5 Sekunden damit das Backend hochfahren kann..." -ForegroundColor Cyan +Start-Sleep -Seconds 5 + +# --------------------------------------------------------------------------- +# 6. Frontend in neuem PowerShell-Fenster starten +# --------------------------------------------------------------------------- +Write-Step "Starte Frontend..." + +$frontendCmd = "Set-Location '$Root\Frontend'; Write-Host 'NexusRMM Frontend' -ForegroundColor Cyan; npm run dev" + +Start-Process powershell -ArgumentList @( + "-NoExit", + "-Command", + $frontendCmd +) -WindowStyle Normal + +Write-OK "Frontend-Fenster geöffnet." + +# --------------------------------------------------------------------------- +# 7. Zusammenfassung +# --------------------------------------------------------------------------- +Write-Host "" +Write-Host "╔══════════════════════════════════════════╗" -ForegroundColor Green +Write-Host "║ NexusRMM ist bereit! ║" -ForegroundColor Green +Write-Host "╠══════════════════════════════════════════╣" -ForegroundColor Green +Write-Host "║ Frontend: http://localhost:5173 ║" -ForegroundColor Green +Write-Host "║ Backend: http://localhost:5000 ║" -ForegroundColor Green +Write-Host "║ Swagger: http://localhost:5000/swagger ║" -ForegroundColor Green +Write-Host "║ gRPC: http://localhost:5001 ║" -ForegroundColor Green +Write-Host "║ MeshCentral: https://localhost:4430 ║" -ForegroundColor Green +Write-Host "╚══════════════════════════════════════════╝" -ForegroundColor Green +Write-Host "" +Write-Host "Agent starten: .\Agent\nexus-agent.exe" -ForegroundColor Yellow +Write-Host "Alles stoppen: .\dev-stop.ps1" -ForegroundColor Yellow diff --git a/dev-stop.ps1 b/dev-stop.ps1 new file mode 100644 index 0000000..a3e1014 --- /dev/null +++ b/dev-stop.ps1 @@ -0,0 +1,95 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Stoppt die NexusRMM Entwicklungsumgebung +.DESCRIPTION + Beendet alle PowerShell-Fenster mit "NexusRMM" im Titel und + fährt den PostgreSQL-Container herunter (ohne Volumes zu löschen). + MeshCentral wird NICHT gestoppt. +#> + +$ErrorActionPreference = "Stop" +$Root = "D:\001_Projekte\IT_Tool" + +# --------------------------------------------------------------------------- +# Helper +# --------------------------------------------------------------------------- +function Write-Step { param($msg) Write-Host "`n==> $msg" -ForegroundColor Cyan } +function Write-OK { param($msg) Write-Host " [OK] $msg" -ForegroundColor Green } +function Write-Warn { param($msg) Write-Host " [!] $msg" -ForegroundColor Yellow } +function Write-Fail { param($msg) Write-Host " [FEHLER] $msg" -ForegroundColor Red } + +# --------------------------------------------------------------------------- +# 1. PowerShell-Fenster mit "NexusRMM" im Hauptfenstertitel schließen +# --------------------------------------------------------------------------- +Write-Step "Schliesse NexusRMM PowerShell-Fenster..." + +Add-Type -AssemblyName System.Diagnostics.Process -ErrorAction SilentlyContinue + +$currentPid = $PID +$killed = 0 + +# GetProcesses liefert alle powershell / pwsh Instanzen +$psProcesses = Get-Process -Name @("powershell", "pwsh") -ErrorAction SilentlyContinue + +foreach ($proc in $psProcesses) { + if ($proc.Id -eq $currentPid) { continue } # dieses Skript selbst nicht beenden + + # Fenstertitel auslesen (MainWindowTitle ist leer bei verborgenen Fenstern) + $title = $proc.MainWindowTitle + if ($title -match "NexusRMM") { + try { + $proc | Stop-Process -Force + Write-OK "Prozess beendet: PID $($proc.Id) – '$title'" + $killed++ + } catch { + Write-Warn "Konnte Prozess PID $($proc.Id) nicht beenden: $_" + } + } +} + +if ($killed -eq 0) { + Write-Warn "Keine laufenden NexusRMM-Fenster gefunden." +} else { + Write-OK "$killed Fenster geschlossen." +} + +# --------------------------------------------------------------------------- +# 2. PostgreSQL-Container stoppen (ohne Volume zu entfernen) +# --------------------------------------------------------------------------- +Write-Step "Stoppe PostgreSQL-Container..." + +# Prüfen ob Docker läuft +$dockerCmd = Get-Command docker -ErrorAction SilentlyContinue +if ($null -eq $dockerCmd) { + Write-Warn "Docker nicht gefunden – überspringe Container-Stop." +} else { + Push-Location $Root + try { + # Nur nexusrmm-postgres stoppen, MeshCentral bleibt unberührt + $containerRunning = docker ps --filter "name=nexusrmm-postgres" --format "{{.Names}}" 2>$null + if ($containerRunning -match "nexusrmm-postgres") { + docker compose stop nexusrmm-postgres + if ($LASTEXITCODE -eq 0) { + Write-OK "nexusrmm-postgres gestoppt." + } else { + Write-Fail "docker compose stop fehlgeschlagen." + } + } else { + Write-Warn "nexusrmm-postgres läuft nicht (bereits gestoppt)." + } + } finally { + Pop-Location + } +} + +# --------------------------------------------------------------------------- +# 3. Zusammenfassung +# --------------------------------------------------------------------------- +Write-Host "" +Write-Host "NexusRMM Entwicklungsumgebung gestoppt." -ForegroundColor Green +Write-Host "Volumes wurden behalten (Datenbankdaten bleiben erhalten)." -ForegroundColor Yellow +Write-Host "MeshCentral wurde nicht gestoppt." -ForegroundColor Yellow +Write-Host "" +Write-Host "Neu starten: .\dev-start.ps1" -ForegroundColor Cyan +Write-Host "Alles inkl. Volumes loeschen: docker compose down -v" -ForegroundColor Cyan