DB startet Server bei ID 0
All checks were successful
Gitea CI/CD / dotnet-build-and-test (push) Successful in 55s
Gitea CI/CD / Set Tag Name (push) Successful in 6s
Gitea CI/CD / docker-build-and-push (push) Successful in 7m42s
Gitea CI/CD / Create Tag (push) Successful in 7s

This commit is contained in:
2025-11-17 15:37:28 +01:00
parent 23cac83061
commit f8961320c5
6 changed files with 490 additions and 17 deletions

View File

@@ -27,6 +27,6 @@ public class ApiController : Controller
public async Task<IActionResult> GetAllServers() public async Task<IActionResult> GetAllServers()
{ {
var Servers = await _context.Servers.OrderBy(s => s.Id).ToListAsync(); var Servers = await _context.Servers.OrderBy(s => s.Id).ToListAsync();
return Ok(); return Ok(Servers);
} }
} }

View File

@@ -83,7 +83,8 @@ public class MetricDto
public class DockerServiceDto public class DockerServiceDto
{ {
public required int Server_id { get; set; } // Vom Watcher-Server zugewiesene ID des Hosts public int Server_id { get; set; } // Vom Watcher-Server zugewiesene ID des Hosts (optional, falls der Agent diese bereits kennt)
public string? IpAddress { get; set; } // IP-Adresse des Servers (wird verwendet, falls Server_id nicht gesetzt oder 0 ist)
public required JsonElement Containers { get; set; } public required JsonElement Containers { get; set; }
} }
@@ -138,9 +139,13 @@ public class MonitoringController : Controller
// Änderungen in Datenbank speichern // Änderungen in Datenbank speichern
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
// Success // Success - Server-ID und IP-Adresse zurückgeben
_logger.LogInformation("Agent für '{server}' erfolgreich registriert.", server.Name); _logger.LogInformation("Agent für '{server}' erfolgreich registriert.", server.Name);
return Ok(); return Ok(new
{
id = server.Id,
ipAddress = server.IPAddress
});
} }
_logger.LogError("Kein Server für Registrierung gefunden"); _logger.LogError("Kein Server für Registrierung gefunden");
return NotFound("No Matching Server found."); return NotFound("No Matching Server found.");
@@ -182,7 +187,7 @@ public class MonitoringController : Controller
// Server in Datenbank finden // Server in Datenbank finden
var server = await _context.Servers var server = await _context.Servers
.FirstOrDefaultAsync(s => s.IPAddress == dto.IpAddress); .FirstOrDefaultAsync(s => s.Id == dto.ServerId);
if (server != null) if (server != null)
{ {
@@ -244,13 +249,32 @@ public class MonitoringController : Controller
return BadRequest(new { error = "Invalid Payload", details = errors }); return BadRequest(new { error = "Invalid Payload", details = errors });
} }
// Prüfen, ob der Server existiert // Debug-Logging für eingehende Requests
var serverExists = await _context.Servers.AnyAsync(s => s.Id == dto.Server_id); _logger.LogDebug("Service-Discovery Request empfangen: Server_id={ServerId}, IpAddress={IpAddress}",
if (!serverExists) dto.Server_id, dto.IpAddress ?? "null");
// Server anhand IP-Adresse oder ID finden
Server? server = null;
// Zuerst versuchen, Server anhand der IP-Adresse zu finden (bevorzugte Methode)
if (!string.IsNullOrEmpty(dto.IpAddress))
{ {
_logger.LogError($"Server with ID {dto.Server_id} does not exist."); server = await _context.Servers.FirstOrDefaultAsync(s => s.IPAddress == dto.IpAddress);
return BadRequest(new { error = "Server not found", details = $"Server with ID {dto.Server_id} does not exist. Please register the server first." });
} }
// Falls keine IP-Adresse übergeben wurde oder Server nicht gefunden, versuche es mit der ID
else if (dto.Server_id > 0)
{
server = await _context.Servers.FirstOrDefaultAsync(s => s.Id == dto.Server_id);
}
if (server == null)
{
_logger.LogError("Server with IP '{IpAddress}' or ID {ServerId} does not exist.", dto.IpAddress, dto.Server_id);
return BadRequest(new { error = "Server not found", details = $"Server with IP '{dto.IpAddress}' or ID {dto.Server_id} does not exist. Please register the server first." });
}
// Server ID für die weitere Verarbeitung setzen
int serverId = server.Id;
List<Container> newContainers = List<Container> newContainers =
JsonSerializer.Deserialize<List<Container>>(dto.Containers.GetRawText()) JsonSerializer.Deserialize<List<Container>>(dto.Containers.GetRawText())
@@ -258,7 +282,7 @@ public class MonitoringController : Controller
foreach (Container container in newContainers) foreach (Container container in newContainers)
{ {
container.ServerId = dto.Server_id; container.ServerId = serverId;
// Debug Logs // Debug Logs
// TODO entfernen wenn fertig getestet // TODO entfernen wenn fertig getestet
Console.WriteLine("---------"); Console.WriteLine("---------");
@@ -272,7 +296,7 @@ public class MonitoringController : Controller
// Liste aller Container, die bereits der übergebenen ServerId zugewiesen sind // Liste aller Container, die bereits der übergebenen ServerId zugewiesen sind
List<Container> existingContainers = _context.Containers List<Container> existingContainers = _context.Containers
.Where(c => c.ServerId == dto.Server_id) .Where(c => c.ServerId == serverId)
.ToList(); .ToList();
@@ -291,7 +315,7 @@ public class MonitoringController : Controller
existingContainer.Image = container.Image; existingContainer.Image = container.Image;
existingContainer.IsRunning = true; existingContainer.IsRunning = true;
_logger.LogInformation("Container '{containerName}' (ID: {containerId}) already exists for Server {serverId}, updated.", container.Name, container.ContainerId, dto.Server_id); _logger.LogInformation("Container '{containerName}' (ID: {containerId}) already exists for Server {serverId}, updated.", container.Name, container.ContainerId, serverId);
} }
// Container auf einen Host/Server registrieren // Container auf einen Host/Server registrieren
else else
@@ -393,6 +417,7 @@ public class MonitoringController : Controller
return NotFound(); return NotFound();
} }
[Authorize]
[HttpGet("cpu-usage")] [HttpGet("cpu-usage")]
public async Task<IActionResult> GetCpuUsageData(int serverId, int hours = 1) public async Task<IActionResult> GetCpuUsageData(int serverId, int hours = 1)
{ {
@@ -413,6 +438,7 @@ public class MonitoringController : Controller
return Ok(data); return Ok(data);
} }
[Authorize]
[HttpGet("ram-usage")] [HttpGet("ram-usage")]
public async Task<IActionResult> GetRamUsageData(int serverId, int hours = 1) public async Task<IActionResult> GetRamUsageData(int serverId, int hours = 1)
{ {
@@ -433,6 +459,7 @@ public class MonitoringController : Controller
return Ok(data); return Ok(data);
} }
[Authorize]
[HttpGet("gpu-usage")] [HttpGet("gpu-usage")]
public async Task<IActionResult> GetGpuUsageData(int serverId, int hours = 1) public async Task<IActionResult> GetGpuUsageData(int serverId, int hours = 1)
{ {
@@ -453,6 +480,7 @@ public class MonitoringController : Controller
return Ok(data); return Ok(data);
} }
[Authorize]
[HttpGet("current-metrics/{serverId}")] [HttpGet("current-metrics/{serverId}")]
public async Task<IActionResult> GetCurrentMetrics(int serverId) public async Task<IActionResult> GetCurrentMetrics(int serverId)
{ {
@@ -509,9 +537,7 @@ public class MonitoringController : Controller
// Degree Input auf zwei Nachkommastellen runden // Degree Input auf zwei Nachkommastellen runden
public static double SanitizeInput(double metricInput) public static double SanitizeInput(double metricInput)
{ {
Math.Round(metricInput, 2); return Math.Round(metricInput, 2);
return metricInput;
} }
private List<Container> ParseServiceDiscoveryInput(int serverId, List<Container> containers) private List<Container> ParseServiceDiscoveryInput(int serverId, List<Container> containers)

View File

@@ -41,5 +41,19 @@ public class AppDbContext : DbContext
optionsBuilder.UseSqlite(connStr); optionsBuilder.UseSqlite(connStr);
} }
} }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Server IDs bei 0 starten lassen (statt Standard 1)
modelBuilder.Entity<Server>()
.Property(s => s.Id)
.ValueGeneratedOnAdd();
// SQLite-spezifische Konfiguration: AUTOINCREMENT startet bei 0
modelBuilder.Entity<Server>()
.ToTable(tb => tb.HasCheckConstraint("CK_Server_Id", "Id >= 0"));
}
} }

View File

@@ -0,0 +1,395 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Watcher.Data;
#nullable disable
namespace Watcher.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20251117142850_StartServerIdsAtZero")]
partial class StartServerIdsAtZero
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.6");
modelBuilder.Entity("Watcher.Models.Container", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ContainerId")
.HasColumnType("TEXT")
.HasAnnotation("Relational:JsonPropertyName", "id");
b.Property<string>("Image")
.HasColumnType("TEXT")
.HasAnnotation("Relational:JsonPropertyName", "image");
b.Property<int?>("ImageId")
.HasColumnType("INTEGER");
b.Property<bool>("IsRunning")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasColumnType("TEXT")
.HasAnnotation("Relational:JsonPropertyName", "name");
b.Property<int>("ServerId")
.HasColumnType("INTEGER")
.HasAnnotation("Relational:JsonPropertyName", "Server_id");
b.Property<int?>("TagId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("ImageId");
b.HasIndex("ServerId");
b.HasIndex("TagId");
b.ToTable("Containers");
});
modelBuilder.Entity("Watcher.Models.ContainerMetric", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<double>("CPU_Load")
.HasColumnType("REAL");
b.Property<double>("CPU_Temp")
.HasColumnType("REAL");
b.Property<int?>("ContainerId")
.HasColumnType("INTEGER");
b.Property<double>("RAM_Load")
.HasColumnType("REAL");
b.Property<double>("RAM_Size")
.HasColumnType("REAL");
b.Property<DateTime>("Timestamp")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("ContainerMetrics");
});
modelBuilder.Entity("Watcher.Models.Image", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<string>("Tag")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Images");
});
modelBuilder.Entity("Watcher.Models.LogEvent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int?>("ContainerId")
.HasColumnType("INTEGER");
b.Property<string>("Level")
.HasColumnType("TEXT");
b.Property<string>("Message")
.HasColumnType("TEXT");
b.Property<int?>("ServerId")
.HasColumnType("INTEGER");
b.Property<DateTime>("Timestamp")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ContainerId");
b.HasIndex("ServerId");
b.ToTable("LogEvents");
});
modelBuilder.Entity("Watcher.Models.Metric", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<double>("CPU_Load")
.HasColumnType("REAL");
b.Property<double>("CPU_Temp")
.HasColumnType("REAL");
b.Property<double>("DISK_Size")
.HasColumnType("REAL");
b.Property<double>("DISK_Temp")
.HasColumnType("REAL");
b.Property<double>("DISK_Usage")
.HasColumnType("REAL");
b.Property<double>("GPU_Load")
.HasColumnType("REAL");
b.Property<double>("GPU_Temp")
.HasColumnType("REAL");
b.Property<double>("GPU_Vram_Size")
.HasColumnType("REAL");
b.Property<double>("GPU_Vram_Usage")
.HasColumnType("REAL");
b.Property<double>("NET_In")
.HasColumnType("REAL");
b.Property<double>("NET_Out")
.HasColumnType("REAL");
b.Property<double>("RAM_Load")
.HasColumnType("REAL");
b.Property<double>("RAM_Size")
.HasColumnType("REAL");
b.Property<int?>("ServerId")
.HasColumnType("INTEGER");
b.Property<DateTime>("Timestamp")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Metrics");
});
modelBuilder.Entity("Watcher.Models.Server", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("CpuCores")
.HasColumnType("INTEGER");
b.Property<double>("CpuLoadCritical")
.HasColumnType("REAL");
b.Property<double>("CpuLoadWarning")
.HasColumnType("REAL");
b.Property<double>("CpuTempCritical")
.HasColumnType("REAL");
b.Property<double>("CpuTempWarning")
.HasColumnType("REAL");
b.Property<string>("CpuType")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("DiskSpace")
.HasColumnType("TEXT");
b.Property<double>("DiskTempCritical")
.HasColumnType("REAL");
b.Property<double>("DiskTempWarning")
.HasColumnType("REAL");
b.Property<double>("DiskUsageCritical")
.HasColumnType("REAL");
b.Property<double>("DiskUsageWarning")
.HasColumnType("REAL");
b.Property<double>("GpuLoadCritical")
.HasColumnType("REAL");
b.Property<double>("GpuLoadWarning")
.HasColumnType("REAL");
b.Property<double>("GpuTempCritical")
.HasColumnType("REAL");
b.Property<double>("GpuTempWarning")
.HasColumnType("REAL");
b.Property<string>("GpuType")
.HasColumnType("TEXT");
b.Property<string>("IPAddress")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("IsOnline")
.HasColumnType("INTEGER");
b.Property<bool>("IsVerified")
.HasColumnType("INTEGER");
b.Property<DateTime>("LastSeen")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<double>("RamLoadCritical")
.HasColumnType("REAL");
b.Property<double>("RamLoadWarning")
.HasColumnType("REAL");
b.Property<double>("RamSize")
.HasColumnType("REAL");
b.Property<int?>("TagId")
.HasColumnType("INTEGER");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TagId");
b.ToTable("Servers", t =>
{
t.HasCheckConstraint("CK_Server_Id", "Id >= 0");
});
});
modelBuilder.Entity("Watcher.Models.Tag", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Tags");
});
modelBuilder.Entity("Watcher.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<DateTime>("LastLogin")
.HasColumnType("TEXT");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Watcher.Models.Container", b =>
{
b.HasOne("Watcher.Models.Image", null)
.WithMany("Containers")
.HasForeignKey("ImageId");
b.HasOne("Watcher.Models.Server", "Server")
.WithMany()
.HasForeignKey("ServerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Watcher.Models.Tag", null)
.WithMany("Containers")
.HasForeignKey("TagId");
b.Navigation("Server");
});
modelBuilder.Entity("Watcher.Models.LogEvent", b =>
{
b.HasOne("Watcher.Models.Container", "Container")
.WithMany()
.HasForeignKey("ContainerId");
b.HasOne("Watcher.Models.Server", "Server")
.WithMany()
.HasForeignKey("ServerId");
b.Navigation("Container");
b.Navigation("Server");
});
modelBuilder.Entity("Watcher.Models.Server", b =>
{
b.HasOne("Watcher.Models.Tag", null)
.WithMany("Servers")
.HasForeignKey("TagId");
});
modelBuilder.Entity("Watcher.Models.Image", b =>
{
b.Navigation("Containers");
});
modelBuilder.Entity("Watcher.Models.Tag", b =>
{
b.Navigation("Containers");
b.Navigation("Servers");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,35 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Watcher.Migrations
{
/// <inheritdoc />
public partial class StartServerIdsAtZero : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddCheckConstraint(
name: "CK_Server_Id",
table: "Servers",
sql: "Id >= 0");
// Bestehende Server-IDs um 1 verringern (1 -> 0, 2 -> 1, etc.)
migrationBuilder.Sql(@"
UPDATE Servers SET Id = Id - 1;
UPDATE Metrics SET ServerId = ServerId - 1 WHERE ServerId IS NOT NULL;
UPDATE Containers SET ServerId = ServerId - 1 WHERE ServerId IS NOT NULL;
UPDATE sqlite_sequence SET seq = seq - 1 WHERE name = 'Servers';
");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropCheckConstraint(
name: "CK_Server_Id",
table: "Servers");
}
}
}

View File

@@ -288,7 +288,10 @@ namespace Watcher.Migrations
b.HasIndex("TagId"); b.HasIndex("TagId");
b.ToTable("Servers"); b.ToTable("Servers", t =>
{
t.HasCheckConstraint("CK_Server_Id", "Id >= 0");
});
}); });
modelBuilder.Entity("Watcher.Models.Tag", b => modelBuilder.Entity("Watcher.Models.Tag", b =>